Exemplo n.º 1
0
def plotAnimated3D(data, date_range):
    data = np.array(data)
    lats = np.unique(data[0, :, 0])
    lons = np.unique(data[0, :, 1])
    frames = []
    for i, cities in enumerate(data):
        frames += [
            go.Frame(
                data=[
                    go.Surface(z=getMatrix(lats, lons, cities), x=lats, y=lons)
                ],
                layout=go.Layout(
                    title=date_range[i],
                    scene=dict(zaxis=dict(range=[0, 1], autorange=False))))
        ]

    fig = go.Figure(
        data=frames[0]['data'],
        layout=go.Layout(updatemenus=[
            dict(type="buttons",
                 buttons=[dict(label="Play", method="animate", args=[None])])
        ], ),
        frames=frames)

    ply.plot(fig,
             filename=tempfile.NamedTemporaryFile(prefix='plot_').name,
             config={
                 'showLink': True,
                 'plotlyServerURL': 'https://chart-studio.plotly.com'
             })
Exemplo n.º 2
0
 def setUp(self):
     # Construct initial scatter object
     self.figure = go.Figure(data=[go.Scatter(y=[3, 2, 1],
                                              marker={'color': 'green'})],
                             layout={'xaxis': {'range': [-1, 4]}},
                             frames=[go.Frame(
                                 layout={'yaxis':
                                         {'title': 'f1'}})])
Exemplo n.º 3
0
    def animate(
        self,
        nframes,
        step = 1,
        path = None
    ):

        frames = []
        for i in range(1, nframes, step):
            i_emb = HyperbolicVec.load(os.path.join(self.path, "embedding%d.bin" % i))
            frames.append(
                go.Frame(data=self.gobjs(i_emb, init=False))
            )
        r = max(map(lambda v : np.linalg.norm(v), (i_emb.project(w) for w in i_emb.keys()))) + 0.05

        fig = go.Figure(
            data = self.gobjs(self.emb, r=r),
            frames = frames,
            layout = Vizualiser.__layout()
        )
        fig.update_layout(
            updatemenus=[
                dict(
                    type="buttons",
                    buttons=[
                        dict(
                            label="Play",
                            method="animate",
                            args=[
                                None,
                                {
                                    "frame": {
                                        "duration": 500,
                                        "redraw": False
                                    },
                                    "fromcurrent": True,
                                    "transition": {
                                        "duration": 500,
                                        "easing": "quadratic-in-out"
                                    }
                                }
                            ]
                        )
                    ],
                    showactive=False
                )
            ]
        )

        if self.__interactive or path is None:
            if path is not None and path.split('.')[-1] == 'html':
                pyo.plot(fig, filename=path, auto_open=True)
            else:
                pyo.plot(fig, filename='temp-plot.html' if path is None else '%s.html' % path, auto_open=True)
        else:
            raise ValueError('Animated plot are not serializable.')
            #fig.write_image(path)
Exemplo n.º 4
0
 def setUp(self):
     # Construct initial scatter object
     self.figure = go.Figure(
         data=[
             go.Scatter(y=[3, 2, 1], marker={"color": "green"}),
             go.Bar(y=[3, 2, 1, 0, -1], marker={"opacity": 0.5}),
         ],
         layout={"xaxis": {"range": [-1, 4]}, "width": 1000},
         frames=[go.Frame(layout={"yaxis": {"title": "f1"}})],
     )
def create_frame(G, inflight_vectors, t):
    #here G is a networkx graph object
    [edge_trace, middle_node_trace] = create_edge_trace(G, inflight_vectors)
    node_trace = create_node_trace(G)
    frame = go.Frame(
        data=[node_trace, middle_node_trace, edge_trace],
        group='nodes',
        name='nodes at time ' +
        str(t))  #should change code from here, just naming is wrong
    return [frame, node_trace, edge_trace]
Exemplo n.º 6
0
 def add_model_iteration_frame(w, final=False):
     a, b = -w[0] / w[1], -w[2] / w[1]
     model = lambda x: a * x + b
     plotter.update_model_area_plots(model)
     frames.append(
         go.Frame(
             data=deepcopy(plotter.figure.data[:2]),
             layout=dict(
                 title=
                 f"{'Final' if final else ''} Model: {a:.2f}*x {'+' if b > 0 else '-'} {abs(b):.2f}"
             )))
    def test_attr_access(self):
        scatt_uid = self.figure.data[0].uid
        self.assertEqual(self.figure.data, (go.Scatter(
            y=[3, 2, 1], marker={'color': 'green'}, uid=scatt_uid), ))

        self.assertEqual(self.figure.layout,
                         go.Layout(xaxis={'range': [-1, 4]}))

        self.assertEqual(self.figure.frames,
                         (go.Frame(layout={'yaxis': {
                             'title': 'f1'
                         }}), ))
Exemplo n.º 8
0
    def setUp(self):
        # Construct initial scatter object
        self.figure = go.Figure(data=[
            go.Scatter(y=[3, 2, 1], marker={'color': 'green'}),
            go.Bar(y=[3, 2, 1, 0, -1], marker={'opacity': 0.5})],
                                layout={'xaxis': {'range': [-1, 4]}},
                                frames=[go.Frame(
                                    layout={'yaxis':
                                            {'title': 'f1'}})])

        # Mock out the message method
        self.figure._send_addTraces_msg = MagicMock()
Exemplo n.º 9
0
    def setUp(self):
        # Construct initial scatter object
        self.figure = go.Figure(
            data=[
                go.Scatter(y=[3, 2, 1], marker={"color": "green"}),
                go.Bar(y=[3, 2, 1, 0, -1], marker={"opacity": 0.5}),
            ],
            layout={"xaxis": {"range": [-1, 4]}},
            frames=[go.Frame(layout={"yaxis": {"title": "f1"}})],
        )

        # Mock out the message method
        self.figure._send_addTraces_msg = MagicMock()
Exemplo n.º 10
0
    def setUp(self):
        # Disable default template
        pio.templates.default = None

        # Construct initial scatter object
        self.figure = go.Figure(
            data=[go.Scatter(y=[3, 2, 1], marker={"color": "green"})],
            layout={"xaxis": {
                "range": [-1, 4]
            }},
            frames=[go.Frame(layout={"yaxis": {
                "title": "f1"
            }})],
        )
Exemplo n.º 11
0
    def test_to_ordered_with_frames(self):
        frame = go.Frame(layout={
            'yaxis': {
                'range': [1, 2]
            },
            'xaxis': {
                'range': [1, 2]
            },
            'shapes': [{
                'xsizemode': 'pixel',
                'type': 'circle'
            }, {
                'type': 'line',
                'xsizemode': 'pixel'
            }]
        },
                         data=[{
                             'type': 'scatter',
                             'marker': {
                                 'size': 12,
                                 'color': 'green'
                             }
                         }, {
                             'type': 'bar',
                             'y': [1, 2],
                             'x': [1, 2]
                         }])

        fig = go.Figure(frames=[{}, frame])
        result = fig.to_ordered_dict()

        expected_frame = OrderedDict([
            ('data', [
                OrderedDict([('marker',
                              OrderedDict([('color', 'green'), ('size', 12)])),
                             ('type', 'scatter')]),
                OrderedDict([('type', 'bar'), ('x', [1, 2]), ('y', [1, 2])])
            ]),
            ('layout',
             OrderedDict([('shapes', [
                 OrderedDict([('type', 'circle'), ('xsizemode', 'pixel')]),
                 OrderedDict([('type', 'line'), ('xsizemode', 'pixel')])
             ]), ('xaxis', OrderedDict([('range', [1, 2])])),
                          ('yaxis', OrderedDict([('range', [1, 2])]))]))
        ])

        expected = OrderedDict([('data', []), ('layout', OrderedDict()),
                                ('frames', [OrderedDict(), expected_frame])])

        self.assertEqual(result, expected)
Exemplo n.º 12
0
    def test_attr_access(self):
        scatt_uid = self.figure.data[0].uid
        self.assertEqual(
            self.figure.data,
            (go.Scatter(y=[3, 2, 1], marker={"color": "green"},
                        uid=scatt_uid), ),
        )

        self.assertEqual(self.figure.layout,
                         go.Layout(xaxis={"range": [-1, 4]}))

        self.assertEqual(self.figure.frames,
                         (go.Frame(layout={"yaxis": {
                             "title": "f1"
                         }}), ))
Exemplo n.º 13
0
 def setUp(self):
     # Construct initial scatter object
     self.figure = go.Figure(
         data=[
             go.Scatter(y=[3, 2, 1], marker={'color': 'green'}),
             go.Bar(y=[3, 2, 1, 0, -1], marker={'opacity': 0.5})
         ],
         layout={
             'xaxis': {
                 'range': [-1, 4]
             },
             'width': 1000
         },
         frames=[go.Frame(layout={'yaxis': {
             'title': 'f1'
         }})])
Exemplo n.º 14
0
    def Frame(self, col, min, max):
        config = copy.deepcopy(self.config)
        config['locked']['sizeCol'] = col
        config['locked']['textCol'] = self.yCol
        #frames.append(go.Frame(name = col , data=Chart("scatter" ,self.DataFrame , col , self.yCol , self.config).GetChartTrace()))
        self.frames.append(
            go.Frame(name=col,
                     data=Chart("scatter", self.DataFrame, col, self.yCol,
                                config).GetChartTrace()))
        #pdb.set_trace()
        min = min if self.DataFrame[col].min(
        ) > min else self.DataFrame[col].min()
        max = max if self.DataFrame[col].max(
        ) < max else self.DataFrame[col].max()

        self.sliders_dict['steps'].append(self.GetSliderStep(col))
        return min, max
Exemplo n.º 15
0
def make_evolution_plots(sim_file, output_html='output.html'):
    # make data
    fname = sim_file
    with open(fname, 'r') as f:
        file_dict = json.load(f)

    all_data = file_dict['data']

    # Figure basics
    # vertical/horizontal lines
    vline = {
        "mode": "lines",
        "x": [0, 0],
        "y": [-1, 1],
        "showlegend": False,
        "line": {
            "color": "#000000",
            "width": 0.8
        },
        "hoverinfo": 'skip',
    }
    hline = {
        "mode": "lines",
        "x": [-1, 1],
        "y": [0, 0],
        "showlegend": False,
        "line": {
            "color": "#000000",
            "width": 0.8
        },
        "hoverinfo": 'skip',
    }

    # Annotations
    auth = {
        'text': '<b>authoritarian</b>',
        'font': {
            "family": "Arial",
            "size": 20
        },
        'x': 0.5,
        'xanchor': 'center',
        'xref': 'paper',
        'y': 1.02,
        'yanchor': 'bottom',
        'yref': 'paper',
        'showarrow': False,
    }
    lib = {
        'text': '<b>libertarian</b>',
        'font': {
            "family": "Arial",
            "size": 20
        },
        'x': 0.5,
        'xanchor': 'center',
        'xref': 'paper',
        'y': -0.08,
        'yanchor': 'bottom',
        'yref': 'paper',
        'showarrow': False,
    }
    left = {
        'text': '<b>left</b>',
        'font': {
            "family": "Arial",
            "size": 20
        },
        'x': -0.1,
        'xanchor': 'center',
        'xref': 'paper',
        'y': 0.5,
        'yanchor': 'bottom',
        'yref': 'paper',
        'showarrow': False,
    }
    right = {
        'text': '<b>right</b>',
        'font': {
            "family": "Arial",
            "size": 20
        },
        'x': 1.1,
        'xanchor': 'center',
        'xref': 'paper',
        'y': 0.5,
        'yanchor': 'bottom',
        'yref': 'paper',
        'showarrow': False,
    }

    layout = dict(xaxis={
        "tickmode": 'array',
        "tickvals": [],
        "range": [-1, 1],
        "autorange": False,
        "zeroline": True
    },
                  yaxis={
                      "tickmode": 'array',
                      "tickvals": [],
                      "range": [-1, 1],
                      "autorange": False,
                      "zeroline": True
                  },
                  updatemenus=[
                      dict(type="buttons",
                           direction="left",
                           buttons=list([
                               dict(args=[
                                   None, {
                                       "frame": {
                                           "duration": 100,
                                           "redraw": False
                                       },
                                       "fromcurrent": True,
                                       "transition": {
                                           "duration": 1000,
                                           "easing": "linear"
                                       }
                                   }
                               ],
                                    label="Play",
                                    method="animate"),
                               dict(args=[[None], {
                                   "frame": {
                                       "duration": 0,
                                       "redraw": False
                                   },
                                   "mode": "immediate",
                                   "transition": {
                                       "duration": 0
                                   }
                               }],
                                    label="Pause",
                                    method="animate")
                           ]),
                           pad={
                               "r": 10,
                               "t": 10
                           },
                           active=0,
                           showactive=True,
                           x=-0.2,
                           xanchor="left",
                           y=-0.1,
                           yanchor="bottom"),
                  ])

    fig = go.Figure(data=[], layout=layout, frames=[])

    frames = []
    for step in range(len(all_data)):
        curr_data = all_data[str(step)]
        individuals_dict = {
            "name": 'individuals',
            "mode": "markers",
            "type": "scatter",
            "x": [ind['x'] for ind in curr_data['individuals']],
            "y": [ind['y'] for ind in curr_data['individuals']],
            "showlegend": False,
            "marker": {
                "size": 2,
                "color": '#000000'
            },
            "hoverinfo": 'skip',
        }

        xx = []
        yy = []
        cc = []
        for m in curr_data['media']:
            xx.append(m['x'])
            yy.append(m['y'])
            if not m['active']:
                cc.append('rgba(0,0,0,0)')
            elif m['x'] < 0 and m['y'] < 0:
                cc.append('rgba(81, 184, 108, .4)')
            elif m['x'] > 0 and m['y'] < 0:
                cc.append('rgba(175, 81, 184, .4)')
            elif m['x'] < 0 and m['y'] > 0:
                cc.append('rgba(184, 81, 81, .4)')
            elif m['x'] > 0 and m['y'] > 0:
                cc.append('rgba(81, 138, 184, .4)')
        media_dict = {
            "name": 'media',
            "mode": "markers",
            "type": "scatter",
            "x": xx,
            "y": yy,
            "showlegend": False,
            "marker": {
                "size": 10,
                "color": cc
            },
            "hoverinfo": 'skip',
        }

        if step == 0:
            fig.add_trace(go.Scatter(individuals_dict))
            fig.add_trace(go.Scatter(media_dict))

        # make frames
        frame = {
            "data": [go.Scatter(individuals_dict),
                     go.Scatter(media_dict)],
            "name": str(step),
            "traces": [0, 1]
        }
        frames.append(frame)

    fig.add_trace(go.Scatter(vline))
    fig.add_trace(go.Scatter(hline))
    fig["frames"] = [go.Frame(fr) for fr in frames]

    fig.layout['plot_bgcolor'] = "rgba(0,0,0,0)"
    fig.layout['paper_bgcolor'] = "rgba(0,0,0,0)"
    fig.layout['width'] = 600
    fig.layout['height'] = 500
    fig.layout['margin']['l'] = 80
    fig.layout['margin']['r'] = 120
    fig.layout['margin']['t'] = 50
    fig.layout['margin']['b'] = 80
    fig.layout['margin']['autoexpand'] = False

    # Write to html
    fig.write_html(output_html,
                   config={
                       'showLink': False,
                       'displayModeBar': False
                   })
Exemplo n.º 16
0
    def show_evolution(self):
        fig = go.Figure(layout=layout)
        surface = fig.add_surface(z=self.u[0].T, colorscale='YlGnBu')
        fig.layout.scene.zaxis.range = [np.min(self.u), np.max(self.u)]
        fig.layout.scene.yaxis.range = [self.Y_START, self.Y_END]
        fig.layout.scene.xaxis.range = [self.X_START, self.X_END]

        frames = []
        for j in range(self.J):
            frames.append(
                go.Frame(data=[{
                    'type': 'surface',
                    'x': self.x,
                    'y': self.y,
                    'z': self.u[j].T
                }]))

        fig.frames = frames
        fig.layout.updatemenus = [{
            'buttons': [{
                'args': [
                    None, {
                        'frame': {
                            'duration': 100,
                            'redraw': False
                        },
                        'fromcurrent': True,
                        'transition': {
                            'duration': 100
                        }
                    }
                ],
                'label':
                'Play',
                'method':
                'animate'
            }, {
                'args': [[None], {
                    'frame': {
                        'duration': 0,
                        'redraw': False
                    },
                    'mode': 'immediate',
                    'transition': {
                        'duration': 0
                    }
                }],
                'label':
                'Pause',
                'method':
                'animate'
            }],
            'direction':
            'left',
            'pad': {
                'r': 10,
                't': 87
            },
            'showactive':
            False,
            'type':
            'buttons',
            'x':
            0.55,
            'xanchor':
            'right',
            'y':
            0,
            'yanchor':
            'top'
        }]
        display(iplot(fig))
Exemplo n.º 17
0
                               dict(label='Play',
                                    method='animate',
                                    args=[
                                        None,
                                        dict(frame=dict(duration=50,
                                                        redraw=True),
                                             transition=dict(duration=0),
                                             fromcurrent=True,
                                             mode='immediate')
                                    ])
                           ])
                  ])
lon_range = np.arange(-180, 180, 2)

frames = [
    go.Frame(layout=dict(geo_center_lon=lon, geo_projection_rotation_lon=lon))
    for lon in lon_range
]

fig.update(frames=frames)
fig.show()

# https://community.plotly.com/t/animate-rotating-orthographic-map-in-python-plotly/28812/6

from plotly.offline import download_plotlyjs, init_notebook_mode, iplot, plot
init_notebook_mode(connected=True)
iplot(fig,
      auto_play=True)  #or plot(fig, filename='rotation.html', auto_play=True)

import plotly.graph_objs as go
import numpy as np
Exemplo n.º 18
0
                     yaxis=dict(range=[0, 3000], autorange=True, title_text='change'))
)

init = 0

for i in range(1, cluster_graw_rate.shape[1]):
    cluster_grow.add_trace(
        go.Scatter(x=[cluster_graw_rate.loc[init, 'Date']],
                   y=[cluster_graw_rate.loc[init, cluster_graw_rate.columns[i]]],
                   name=cluster_graw_rate.columns[i],
                   mode='lines', line=dict(color=line_colors[i - 1],
                                           width=3.2))
    )

cluster_grow.update(frames=[go.Frame(data=[go.Scatter(x=cluster_graw_rate.loc[:k, 'Date'],
                                                      y=cluster_graw_rate.loc[:k, col]) for col in
                                           cluster_graw_rate.columns[1:]]) for k in
                            range(init + 1, cluster_graw_rate.shape[0], 5)])

cluster_grow.update_layout(updatemenus=[dict(buttons=list([dict(label='play',
                                                                method='animate',
                                                                args=[None, {'frame': {'duration': 300}}])]),
                                             font=dict(size=16,
                                                       color='#fff'),
                                             bordercolor='#fff'
                                             )])
cluster_grow.update_layout(
    title=dict(text='Cluster growing rate',
               font=dict(color='#fff')),
    xaxis=dict(title='Date',
               showgrid=False,
Exemplo n.º 19
0
    leg = racemap_df
    leg["leg"] = i
    route_df.append(leg)

fig = go.Figure()

srd = racemap_df.sort_values(by = "val", ascending=True).reset_index(drop=True)

frames = list()
lon_data = [srd.lon[0]]
lat_data = [srd.lat[0]]

for i in range(len(srd.lon)):
    if i % 10 == 0:
        frames.append(
            go.Frame(data=[go.Scattergeo(lon=lon_data, lat=lat_data)])
        )
        lon_data.append(srd.lon[i])
        lat_data.append(srd.lat[i])

lon_data.append(srd.lon[i])
lat_data.append(srd.lat[i])
frames.append(go.Frame(data=[go.Scattergeo(lon=lon_data, lat=lat_data)]))

fig = go.Figure()

srd = all_legs

frames = list()
lon_data = [all_legs.lon[0]]
lat_data = [all_legs.lat[0]]
Exemplo n.º 20
0
    def _create_nodes_frames_2d(self):
        colorbar = go.scatter.marker.ColorBar(title="", thickness=10, x=-0.05)
        marker = go.scatter.Marker(
            symbol=self.df["symbol"],
            size=self.nodesize * 2,
            color=self.df["age"],
            colorscale=self.colorscale,
            colorbar=colorbar,
        )

        frames = []
        sliders_dict = dict(
            active=self.start_frame - 1,
            yanchor="top",
            xanchor="left",
            currentvalue={
                "prefix": "Age:",
                "visible": True,
                "xanchor": "right",
            },
            len=0.9,
            x=0.05,
            y=0.1,
            steps=[],
        )

        # get start and end points for bound line plots
        xmin = min([self.pos2d[k][0] for k in self.pos2d])
        xmax = max([self.pos2d[k][0] for k in self.pos2d])

        maxage = max(self.df["age"])
        for a in np.linspace(1, maxage, min(200, maxage)):
            a = int(a)
            adf = self.df[self.df["age"] <= a]
            node_object = go.Scatter(
                x=[self.pos2d[k][0] for k in adf["id"]],
                # y=[self.pos2d[k][1] for k in adf["id"]],
                y=[self.df["objval"][k] for k in adf["id"]],
                mode="markers",
                marker=marker,
                # hovertext=[
                #     f"LP obj: {adf['objval'].iloc[i]:.3f}\
                #     <br>node number: {adf['number'].iloc[i]}\
                #     <br>node age: {adf['age'].iloc[i]}\
                #     <br>depth: {adf['depth'].iloc[i]}\
                #     <br>LP cond: {adf['condition'].iloc[i]:.1f}\
                #     <br>iterations: {adf['iterations'].iloc[i]}"
                #     for i in range(len(adf))
                # ],
                hoverinfo="text+name",
                opacity=0.7,
                name="LP Solutions",
            )
            primalbound = go.Scatter(
                x=[xmin, xmax],
                y=2 * [adf["primalbound"].iloc[-1]],
                mode="lines",
                opacity=0.5,
                name="Primal Bound",
            )
            dualbound = go.Scatter(
                x=[xmin, xmax],
                y=2 * [adf["dualbound"].iloc[-1]],
                mode="lines",
                opacity=0.5,
                name="Dual Bound",
            )

            frames.append(
                go.Frame(data=[node_object, primalbound, dualbound],
                         name=str(a)))

            slider_step = {
                "args": [
                    [a],
                    {
                        "frame": {
                            "redraw": True,
                            "restyle": False
                        },
                        "fromcurrent": True,
                        "mode": "immediate",
                    },
                ],
                "label":
                a,
                "method":
                "animate",
            }
            sliders_dict["steps"].append(slider_step)

        return frames, sliders_dict
    def test_to_ordered_with_frames(self):
        frame = go.Frame(
            layout={
                "yaxis": {
                    "range": [1, 2]
                },
                "xaxis": {
                    "range": [1, 2]
                },
                "shapes": [
                    {
                        "xsizemode": "pixel",
                        "type": "circle"
                    },
                    {
                        "type": "line",
                        "xsizemode": "pixel"
                    },
                ],
            },
            data=[
                {
                    "type": "scatter",
                    "marker": {
                        "size": 12,
                        "color": "green"
                    }
                },
                {
                    "type": "bar",
                    "y": [1, 2],
                    "x": [1, 2]
                },
            ],
        )

        fig = go.Figure(frames=[{}, frame])
        result = fig.to_ordered_dict()

        expected_frame = OrderedDict([
            (
                "data",
                [
                    OrderedDict([
                        (
                            "marker",
                            OrderedDict([("color", "green"), ("size", 12)]),
                        ),
                        ("type", "scatter"),
                    ]),
                    OrderedDict([("type", "bar"), ("x", [1, 2]), ("y", [1,
                                                                        2])]),
                ],
            ),
            (
                "layout",
                OrderedDict([
                    (
                        "shapes",
                        [
                            OrderedDict([("type", "circle"),
                                         ("xsizemode", "pixel")]),
                            OrderedDict([("type", "line"),
                                         ("xsizemode", "pixel")]),
                        ],
                    ),
                    ("xaxis", OrderedDict([("range", [1, 2])])),
                    ("yaxis", OrderedDict([("range", [1, 2])])),
                ]),
            ),
        ])

        expected = OrderedDict([
            ("data", []),
            ("layout", OrderedDict()),
            ("frames", [OrderedDict(), expected_frame]),
        ])

        self.assertEqual(result, expected)
          go.Scatter(x=x, y=y,
                     mode="lines",
                     line=dict(width=2, color="blue"),
                     name='goal')],
    layout=go.Layout(
        xaxis=dict(range=[xm, xM], autorange=False, zeroline=False),
        yaxis=dict(range=[ym, yM], autorange=False, zeroline=False),
        title_text="Swarm Intelligence Algorithm", hovermode="closest",
        updatemenus=[dict(type="buttons",
                          buttons=[dict(label="Play",
                                        method="update",
                                        args=[None])])]),
    frames=[go.Frame(
            data=[go.Scatter(
            x=list(vet[k][0].T[:][0]),
            y=list(vet[k][0].T[:][1]),
            mode="markers",
            name = 'bee',
            marker=dict(color = "yellow", size=10, 
                         line = dict( color='black', width=2)))])
                         for k in range(N)]
)

iplot(fig)


# In[ ]:




Exemplo n.º 23
0
def load_output(clicks):
    if clicks is None:
        return go.Figure()
    else:
        tabla_distancias, tabla_capitales = importar_tablas()
        mejor_cromosoma = [5, 21, 15, 14, 16, 3, 2, 11, 9, 0, 4, 8, 19, 1, 23, 20, 10, 22, 12, 7, 18, 6, 13, 17, 5]
        cap = formatear(tabla_capitales, mejor_cromosoma)

        # --------------------------- dibujado del mapa
        frames = []
        for k in range(len(cap)):
            frames.append(go.Frame(data=[
                go.Scattermapbox(
                    mode='markers+lines', 
                    lat=cap['latitud'][:k+1],  
                    lon=cap['longitud'][:k+1],
                    marker={'size': 8, 'color': 'red'},
                    line={'color': 'blue', 'width':2})
                ], name=f'frame{k}'))
     
        # dibujo la figura, y le asigno los cuadros
        fig = go.Figure(
            data=go.Scattermapbox(
                lat=cap['latitud'], 
                lon=cap['longitud'],
                text=cap['capital'],
                hoverinfo='text'
            ),
            layout=go.Layout(        
                title_text=f'Recorrido Mínimo: 12817 km    |   Tiempo Ejecución: 84.782 segundos', 
                hovermode="closest",
                font={'size': 18}
            ),
            frames=frames
        )

        updatemenus = [dict(
                buttons = [
                    dict(
                        args = [None, {"frame": {"duration": 1000, "redraw": True},
                                        "fromcurrent": True, 
                                        "transition": {"duration": 500, 'easing': 'cubic-in-out'}
                                    }],
                        label = "Recorrer",
                        method = "animate"
                        ),
                    dict(
                        args = [[None], {"frame": {"duration": 0, "redraw": True},
                                        "mode": "immediate",
                                        "transition": {"duration": 0}}],
                        label = "Pausar",
                        method = "animate"
                        )
                ],
                direction = "left",
                pad = {"r": 10, "t": 87},
                showactive = False,
                type = "buttons",
                x = 0.14,
                xanchor = "right",
                y = 0.16,
                yanchor = "top"
            )]  

        sliders = [dict(steps = [dict(method= 'animate',
                                    args= [[f'frame{k}'],                           
                                    dict(mode= 'immediate',
                                        frame=dict(duration=400, redraw=True),
                                        transition=dict(duration= 0))
                                        ],
                                    label=f'{cap.iloc[k]["capital"]}'
                                    ) for k in range(len(cap))], 
                        active=0,
                        transition={'duration':500 , 'easing': 'cubic-in-out'},
                        x=0, # slider starting position  
                        y=0, 
                        currentvalue=dict(
                            font=dict(size=25), 
                            visible=True, 
                            xanchor= 'center'
                        ),  
                        borderwidth=2,
                        len=1) #slider length
                ]

        fig.update_layout(
            sliders = sliders,
            updatemenus = updatemenus,
            margin={"r":50,"t":50,"l":50,"b":50},
            mapbox_style="open-street-map",
            autosize=True,
            hovermode='closest',
            mapbox=dict(
                center=dict(
                    lat=-35.876958,
                    lon=-65.293389
                ),
                zoom=3
            ),
            height=600
        )
        return fig
Exemplo n.º 24
0
    def show_evolution(self, save=False, filename=None):
        """
        Animate evolution of the solution.
        :param save: if to save on disk
        :param filename: file name to save to
        :return: plotly.graph_objs.Figure with the evolution of the solution
        """
        if filename is None:
            filename = "evolution"
        if not filename.endswith(".html"):
            filename += ".html"
        fig = go.Figure(data=go.Surface(x=self.x, y=self.y, z=self.u[0].T),
                        layout=layout)

        # Scale fix
        fig.layout.scene.zaxis.range = [np.min(self.u), np.max(self.u)]
        fig.layout.scene.yaxis.range = [self.Y_START, self.Y_END]
        fig.layout.scene.xaxis.range = [self.X_START, self.X_END]
        fig.layout.coloraxis.cmin = np.min(self.u)
        fig.layout.coloraxis.cmax = np.max(self.u)
        fig.layout.scene.xaxis.autorange = False
        fig.layout.scene.yaxis.autorange = False
        fig.layout.scene.zaxis.autorange = False

        frames = []
        for j in range(self.J):
            frames.append(
                go.Frame(data=[go.Surface(x=self.x, y=self.y, z=self.u[j].T)]))

        fig.frames = frames

        fig.layout.updatemenus = [{
            "buttons": [
                {
                    "args": [
                        None,
                        {
                            "frame": {
                                "duration": 100,
                                "redraw": True
                            },
                            "fromcurrent": True,
                        },
                    ],
                    "label":
                    "Play",
                    "method":
                    "animate",
                },
                {
                    "args": [
                        [None],
                        {
                            "frame": {
                                "duration": 0,
                                "redraw": True
                            },
                            "mode": "immediate",
                        },
                    ],
                    "label":
                    "Pause",
                    "method":
                    "animate",
                },
            ],
            "direction":
            "left",
            "pad": {
                "r": 10,
                "t": 87
            },
            "showactive":
            False,
            "type":
            "buttons",
            "x":
            0.1,
            "xanchor":
            "right",
            "y":
            0,
            "yanchor":
            "top",
        }]
        if save:
            if not os.path.exists("results"):
                os.makedirs("results")
            plotly.offline.plot(fig, filename=f"results//{filename}")
        return fig
Exemplo n.º 25
0
for i in range(N):
    ax.cla()
    ax.imshow(sat[i,:,:],vmin=0.1, vmax=1.0,origin='lower',aspect=0.015,cmap='viridis_r')  #,extent=[0,100,0,1])
    ax.set_title("frame {}".format(i))
    plt.pause(0.01)

fig = go.Figure(
    data=[go.Heatmap(z=sat[0],zmin=0.1,zmax=1.0)],
    layout=go.Layout(
        title="Time 0",
        title_x=0.1,
        updatemenus=[dict(
            type="buttons",
            buttons=[dict(label="Play",
                          method="animate",
                          args=[None]),
                    dict(label="Pause",
                         method="animate",
                         args=[None,
                               {"frame": {"duration": 0, "redraw": False},
                                "mode": "immediate",
                                "transition": {"duration": 0}}],
                         )])]
    ),
    frames=[go.Frame(data=[go.Heatmap(z=sat[i],zmin=0.1,zmax=1.0)],
                     layout=go.Layout(title_text=f"Timestep {i+1}")) 
            for i in range(1, N)]
)
fig.show()
#st.plotly_chart(fig)
def display_bubble_plot():
    st.header("Animated Bubble Plot")

    data = create_dataframe()
    data = data.sample(n=2000, random_state=1)

    # Define figure
    figure = {'data': [], 'layout': {}, 'frames': []}

    dataset = data
    dataset['month_year'] = pd.to_datetime(
        dataset['month_year']).dt.strftime('%Y-%m')
    years = list(dataset['month_year'].sort_values().unique())

    weekdays = list(dataset['order_purchase_day'].sort_values().unique())
    N = len(weekdays)
    data = []

    year = years[0]

    for day in weekdays:

        df = dataset[(dataset['order_purchase_day'] == day)
                     & (dataset['month_year'] == year)]

        data.append(
            go.Scatter(
                x=df['freight_value'],
                y=df['payment_value'],
                text=df['order_purchase_day'],
                mode='markers',
                marker=dict(
                    size=df['price'],
                    sizemode="area",
                    color=np.random.rand(N),  #set color equal to a variable
                    colorscale='rdylgn',  # one of plotly colorscales
                    showscale=False),
                name=day))

    layout = {
        'xaxis': {
            'title': 'Freight Value',
            #'tickformat' : '%B <br>%Y',
            'type': 'linear',
            #'autorange': True,
            'range': [0, 110],
            'showline': True,
            'showticklabels': True,
            'linecolor': 'rgb(204, 204, 204)',
            'linewidth': 2,
            'ticks': 'outside',
            'tickfont': dict(
                family='Arial',
                size=12,
                color='rgb(82, 82, 82)',
            )
        },
        'yaxis': {
            'title': 'Payment Value',
            #'autorange': True,
            'range': [0, 2500],
            'showline': True,
            'showticklabels': True,
            'linecolor': 'rgb(204, 204, 204)',
            'linewidth': 2,
            'ticks': 'outside',
            'tickfont': dict(
                family='Arial',
                size=12,
                color='rgb(82, 82, 82)',
            )
        },
        'hovermode':
        'closest',
        'showlegend':
        True,
        'title_text':
        "Freight vs Payment Value per Weekday",
        'title_font':
        dict(family='Arial', size=20, color='rgb(82, 82, 82)'),
        'legend_title':
        "Weekday",
        'legend_traceorder':
        "grouped",
        'legend_title_font_color':
        "green",
        'legend_title_font':
        dict(family='Arial', size=15, color='rgb(82, 82, 82)'),
        'plot_bgcolor':
        'rgb(223, 232, 243)',
        'updatemenus': [{
            'buttons': [{
                'args': [
                    None, {
                        'frame': {
                            'duration': 1200,
                            'redraw': True
                        },
                        'fromcurrent': True,
                        'transition': {
                            'duration': 100,
                            'easing': 'quadratic-in-out'
                        }
                    }
                ],
                'label':
                'Play',
                'method':
                'animate'
            }, {
                'args': [[None], {
                    'frame': {
                        'duration': 0,
                        'redraw': False
                    },
                    'mode': 'immediate',
                    'transition': {
                        'duration': 0
                    }
                }],
                'label':
                'Pause',
                'method':
                'animate'
            }],
            'direction':
            'left',
            'pad': {
                'r': 10,
                't': 80
            },
            'showactive':
            False,
            'type':
            'buttons',
            'x':
            0.1,
            'xanchor':
            'right',
            'y':
            0,
            'yanchor':
            'top'
        }],
        'sliders': [{
            'active': 0,
            'yanchor': 'top',
            'xanchor': 'left',
            'currentvalue': {
                'font': {
                    'size': 14
                },
                'prefix': 'Month-Year:',
                'visible': True,
                'xanchor': 'right'
            },
            'transition': {
                'duration': 500,
                'easing': 'cubic-in-out'
            },
            'pad': {
                'b': 10,
                't': 50
            },
            'len': 0.9,
            'x': 0.1,
            'y': 0,
            'steps': []
        }]
    }

    frames = []

    for year in years[1:]:

        frame = {'data': [], 'name': year}

        for day in weekdays:

            df = dataset[(dataset['order_purchase_day'] == day)
                         & (dataset['month_year'] == year)]

            frame['data'].append(
                go.Scatter(
                    x=df['freight_value'],
                    y=df['payment_value'],
                    text=df['order_purchase_day'],
                    mode='markers',
                    marker=dict(
                        size=df['price'],
                        sizemode="area",
                        color=np.random.rand(
                            N),  #set color equal to a variable
                        colorscale='rdylgn',  # one of plotly colorscales
                        showscale=False),
                    name=day))

        frames.append(go.Frame(data=frame['data'], name=frame['name']))

        slider_step = {
            'args': [[year], {
                'frame': {
                    'duration': 1200,
                    'redraw': True
                },
                'mode': 'immediate',
                'transition': {
                    'duration': 500
                }
            }],
            'label':
            year,
            'method':
            'animate'
        }

        layout['sliders'][0]['steps'].append(slider_step)

    fig = go.Figure(data=data, layout=layout, frames=frames)
    return st.plotly_chart(fig)
Exemplo n.º 27
0
               line=dict(color='#bf00ff'))
],
                layout=go.Layout(xaxis=dict(
                    range=[x.min() - 100, x.max() + 100],
                    autorange=False,
                    tickwidth=2,
                    title='Distance From Start'),
                                 yaxis=dict(range=[y.min() - 20,
                                                   y.max() + 20],
                                            autorange=False,
                                            title='Stride Frequency'),
                                 title='My-Graph'),
                frames=[
                    go.Frame(data=[
                        go.Scatter(x=[x[k], x[k]],
                                   y=[y.min() - 20, y.max() + 20],
                                   mode='lines',
                                   marker=dict(color="blue", size=10))
                    ]) for k in range(index[0], index[-1] + 1)
                ])

fig.update_layout(updatemenus=[{
    "buttons": [{
        "args": [
            None, {
                "frame": {
                    "duration": 500,
                    "redraw": False
                },
                "fromcurrent": True,
                "transition": {
                    "duration": 300,
Exemplo n.º 28
0
    arrowsize=1,
    arrowwidth=2,
    arrowcolor="#636363",
    ax=50,
    ay=-50,
    bordercolor="#c7c7c7",
    borderwidth=0,
    borderpad=4,
    bgcolor="hotpink",
    opacity=0.8
)

# Animation
fig.update(frames=[
    go.Frame(
        data=
        go.Scatter(x=df.Year[:k], y=df.Released[:k]), ) for k in range(init, len(df) + 1)])

# hide y ticks!
fig.update_layout(

    xaxis=dict(
        # autorange=True,
        showgrid=False,
        tickmode="array",
        tickvals=[i for i in range(1970, 2021, 5)],
        # ticks=range(1970,2020,5),
        # showticklabels=False
    ),

    yaxis=dict(
                    currentvalue=dict(font=dict(size=20),
                                      prefix="Date: ",
                                      visible=True,
                                      xanchor="right"),
                    pad=dict(b=10, t=10),
                    len=0.875,
                    x=0.125,
                    y=0,
                    steps=[])

fig_frames = []
for day in days:
    frame = go.Frame(data=[
        go.Choroplethmapbox(
            locations=data['Name'],
            customdata=data['Name'],
            z=data[day],
        )
    ],
                     name=day)
    fig_frames.append(frame)

    slider_step = dict(args=[[day],
                             dict(mode="immediate",
                                  frame=dict(duration=3000, redraw=True))],
                       method="animate",
                       label=day)
    sliders_dict["steps"].append(slider_step)

clayout['sliders'] = [sliders_dict]
fig = go.Figure(data=cdata, layout=clayout, frames=fig_frames)
Exemplo n.º 30
0
    def _create_nodes_frames(self):
        colorbar = go.scatter3d.marker.ColorBar(title="",
                                                thickness=10,
                                                x=-0.05)
        marker = go.scatter3d.Marker(
            symbol=self.df["symbol"],
            size=self.nodesize,
            color=self.df["age"],
            colorscale=self.colorscale,
            colorbar=colorbar,
        )

        frames = []
        sliders_dict = dict(
            active=0,
            yanchor="top",
            xanchor="left",
            currentvalue={
                "prefix": "Age:",
                "visible": True,
                "xanchor": "right",
            },
            len=0.9,
            x=0.05,
            y=0.1,
            steps=[],
        )

        # get start and end points for bound line plots
        min_x = min(self.df["x"])
        max_x = max(self.df["x"])
        min_y = min(self.df["y"])
        max_y = max(self.df["y"])

        maxage = max(self.df["age"])
        for a in np.linspace(1, maxage, min(200, maxage)):
            a = int(a)
            adf = self.df[self.df["age"] <= a]
            node_object = go.Scatter3d(
                x=adf["x"],
                y=adf["y"],
                z=adf["objval"],
                mode="markers+text",
                marker=marker,
                hovertext=adf["number"],
                # hovertemplate="LP obj: %{z}<br>node number: %{hovertext}<br>%{marker.color}",
                hoverinfo="z+text+name",
                opacity=0.7,
                name="LP Solutions",
            )

            primalbound = go.Scatter3d(
                x=[min_x, min_x, max_x, max_x, min_x],
                y=[min_y, max_y, max_y, min_y, min_y],
                z=[adf["primalbound"].iloc[-1]] * 5,
                mode="lines",
                line=go.scatter3d.Line(width=5),
                hoverinfo="name+z",
                name="Primal Bound",
                opacity=0.5,
            )
            dualbound = go.Scatter3d(
                x=[min_x, min_x, max_x, max_x, min_x],
                y=[min_y, max_y, max_y, min_y, min_y],
                z=[adf["dualbound"].iloc[-1]] * 5,
                mode="lines",
                line=go.scatter3d.Line(width=5),
                hoverinfo="name+z",
                name="Dual Bound",
                opacity=0.5,
            )

            frames.append(
                go.Frame(data=[node_object, primalbound, dualbound],
                         name=str(a)))

            slider_step = {
                "args": [
                    [a],
                    {
                        "frame": {
                            "redraw": True,
                            "restyle": False
                        },
                        "fromcurrent": True,
                        "mode": "immediate",
                    },
                ],
                "label":
                a,
                "method":
                "animate",
            }
            sliders_dict["steps"].append(slider_step)

        return frames, sliders_dict