Ejemplo n.º 1
0
def plot_cost_and_trace(X, Y, trace, low=-10, high=10, size=100):
    gr = calculate_cost_grid(X, Y, low, high, size)
    lsp = np.linspace(low, high, size)

    contour = go.Contour(z=np.log(gr),
                         x=lsp,
                         y=lsp,
                         colorscale='Jet',
                         contours={'coloring': 'heatmap'})

    descent = go.Scatter(x=trace[:, 1], y=trace[:, 0], mode='markers')

    iplot(
        go.Figure(data=[contour, descent],
                  layout=go.Layout(hovermode='closest', width=600,
                                   height=600)))
Ejemplo n.º 2
0
def contourPlotFeatures(df, prettyNames, typeModel):
    fig = make_subplots(rows=2, cols=2, shared_xaxes=True)

    fig.update_layout(
        {
            "plot_bgcolor": "rgba(0, 0, 0, 0)",
            "paper_bgcolor": "rgba(0, 0, 0, 0)",
        },
        barmode='group',
        autosize=False,
        width=width_plotly,
        height=height_plotly,
        margin=dict(l=0, r=0, t=25, b=0),
        title=go.layout.Title(text=""),
        #xaxis=dict(title="Number principal components"),
        #yaxis=dict(title="Relative importance"),
        font=dict(family="Palatino", color="Black", size=12),
    )
    plotFeatures = ["rB", "dAO", "t"]
    for i in range(len(prettyNames)):

        classifier = joblib.load(
            Path(__file__).resolve().parents[2] / "models" / typeModel /
            Path(prettyNames[i] + ".pkl"))
        plotFeatures = joblib.load(
            Path(__file__).resolve().parents[2] / "models" / typeModel /
            Path(prettyNames[i] + "features.pkl"))

        df["Predictions"] = classifier.predict(df[plotFeatures])
        df["Cubic probability"] = classifier.predict_proba(df[plotFeatures])[:,
                                                                             1]
        Z_grid = np.array(df["Cubic probability"]).reshape(
            points, points, points)

        fig = go.Figure(
            data=go.Contour(
                z=Z_grid[:, 0, :],
                x=feature_rB,  # horizontal axis
                y=feature_t  # vertical axis
            ),
            layout=Layout(title=go.layout.Title(
                text="Probability for perovskite prediction"),
                          scene=layout.Scene(
                              xaxis=dict(title='rB'),
                              yaxis=dict(title='t'),
                          )))
    fig.show()
Ejemplo n.º 3
0
    def plot2d(parameters, data, center, units):
        # makes a 2d plotly graph of the data
        # Will not graph the correct center if data is rotated 90 degrees because of repositioned axes
        detector_data, distance_1, distance_2, pixel_size_x,pixel_size_y, translation, dim_x, dim_y = parameters
        x_units_centered, y_units_centered = units
        X = x_units_centered
        Y = y_units_centered + translation
        Z = data
        graph_data = [go.Contour(z = detector_data, x = X, y = Y)]

        layout = go.Layout(
         xaxis = dict(title = "Milimeters"),
         yaxis = dict(title = "Milimeters"),
         showlegend= False,
         annotations=[
                 dict(
                     x = center[0]/pixel_size_x - detector_data.shape[1]/2,
                     y = (center[1])/pixel_size_y,
                     xref='x',
                     yref='y',
                     text= "Center",
                     showarrow=True,
                     font=dict(
                         family='Courier New, monospace',
                         size=11,
                         color='#000000'
                     ),
                     align = 'center',
                     arrowhead=2,
                     arrowsize=1,
                     arrowwidth=2,
                     arrowcolor='#ffffff',
                     ax=20,
                     ay=-30,
                     bordercolor='#c7c7c7',
                     borderwidth=2,
                     borderpad=4,
                     bgcolor='#ffffff',
                     opacity=0.8
                 )
             ]
         )


        fig = go.Figure(data=graph_data, layout=layout)
        py.plot(fig)
Ejemplo n.º 4
0
    def make_kdeplot(self, varX, varY, a, b, c, d, N, colorsc, title, outdir):
        # varX, varY are lists, 1d numpy.array(s), or dataframe columns, storing the values of two variables

        x, y, Z = self.kde_scipy(varY, varX, a, b, c, d, N)

        trace = [go.Contour(
                z=Z,
                x=x,
                y=y,
                colorscale = colorsc,
                # reversescale=True,
                opacity=0.9,
                contours= dict(showlines = False),
            )]

        layout_comp = go.Layout(
            title=title,
            showlegend=False,
            autosize=True,
            # width=650,
            # height=650,
            xaxis=dict(
                title = 'GC content (%)',
                range=[a, b],
                showgrid=False,
                nticks=7
            ),
            yaxis=dict(
                title= 'Mean Coverage',
                range=[c, d],
                showgrid=False,
                nticks=7
            ),
            margin=go.layout.Margin(
                l=40,
                r=30,
                b=30,
                t=50,
            ),
        )

        fig = go.Figure(data=trace, layout=layout_comp)
        plotly.offline.plot(fig, filename= outdir,
                            auto_open=False, show_link= False,
                            config=dict(displaylogo=False, modeBarButtonsToRemove=['sendDataToCloud'],
                                        showlink=False))
def plot_contour(Z, colorscale):

    data = [go.Contour(z=Z, colorscale=colorscale)]
    axis_layout = dict(showgrid=True, gridcolor='red', showticklabels=True)

    layout = go.Layout(
        width=650,
        height=600,
        autosize=False,
        xaxis=axis_layout,
        yaxis=axis_layout,
    )

    fig = go.Figure(data=data, layout=layout)

    iplot(fig)
    return None
Ejemplo n.º 6
0
def star_2d(img, y, x, size=50, low=10, high=150, spacing=20):

    with fits.open(img) as hdu:
        img_data = hdu[0].data[y - size:y + size, x - size:x + size]

    data = go.Contour(z=img_data,
                      y=np.arange(y - size, y + size + 1),
                      x=np.arange(x - size, x + size + 1),
                      autocontour=False,
                      colorscale='Jet',
                      contours=dict(start=low, end=high, size=spacing))

    layout = go.Layout(autosize=False, height=600, width=600)

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

    return fig
Ejemplo n.º 7
0
def raster_plot(chosen_year, mode):
    raster = df[df.year == chosen_year].sort_values(
        by=['lat', 'lon'], ascending=True)[mode].to_numpy()
    raster = np.reshape(raster, (-1, 144))
    lon = df[df.year == chosen_year].lon.to_numpy()
    lon = np.unique(lon)
    lat = df[df.year == chosen_year].lat.to_numpy()
    lat = np.unique(lat)
    if mode == 'temp':
        cap = 50
    else:
        cap = 4
    data = [
        go.Contour(z=raster,
                   x=lon,
                   y=lat,
                   colorscale="RdBu",
                   reversescale=True,
                   zauto=False,
                   zmin=-cap,
                   zmax=cap)
    ]
    full_data = countries_data + data
    title = 'kinda hot'
    axis_style = dict(
        zeroline=False,
        showline=False,
        showgrid=False,
        ticks='',
        showticklabels=False,
    )
    layout = go.Layout(
        #title=title,
        showlegend=False,  # highlight closest point on hover
        xaxis=dict(
            axis_style,
            range=[lon[0], lon[-1]]  # restrict y-axis to range of lon
        ),
        yaxis=dict(axis_style, ),
        autosize=True,
        #width=1000,
        #height=500,
        margin=dict(l=0, b=50, r=0, t=50))
    fig = go.Figure(data=full_data, layout=layout)
    return fig
Ejemplo n.º 8
0
def plot():

    mx = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1]
    my = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1]
    mz = [[0 for x in range(10)] for y in range(10)]

    for x in range(len(mx)):
        for y in range(len(mx)):
            global mean_s
            mean_s = 0.0
            if y > x:
                m = generate_matrix(50)
                m = populate_matrix(m, 3, [0.33, 0.33, 0.34], 75)
                it = 0
                s = calculate_satisfation(m, mx[x], my[y])
                while len(s) > 0:
                    m = moving_to_random(m, s)
                    s = calculate_satisfation(m, mx[x], my[y])
                    it += 1
                    if it > 1000:
                        break
                mz[x][y] = float(mean_s)
                print mean_s
            else:
                mz[x][y] = float(mean_s)
                print '({},{})\t{}'.format(mx[x], my[y], mz[x][y])

        print mz

# mz = [
#        [0.0, 0.4508647619047619, 0.4496752380952378, 0.3560033333333331, 0.3014742857142886, 0.3337709523809551, 0.3711800000000024, 0.41911666666666697, 0.44966190476190443, 0.4754123809523805],
#        [0.0, 0.0, 0.450681904761904, 0.433738571428572, 0.3460419047619064, 0.33059857142857246, 0.3805328571428591, 0.42845380952380974, 0.49392761904761956, 0.509778095238096],
#        [0.0, 0.0, 0.0, 0.44562476190476136, 0.4388652380952384, 0.44037285714285773, 0.4526504761904761, 0.5025661904761891, 0.5621900000000012, 0.6882757142857162],
#        [0.0, 0.0, 0.0, 0.0, 0.4565504761904761, 0.45610761904761865, 0.4767585714285714, 0.5154728571428577, 0.6016885714285748, 0.7458323809523839],
#        [0.0, 0.0, 0.0, 0.0, 0.0, 0.4572161904761909, 0.4691385714285705, 0.5160771428571425, 0.5944390476190496, 0.8015219047619059],
#        [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.4582071428571421, 0.5062747619047607, 0.5961104761904776, 0.8844371428571418],
#        [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.46510666666666695, 0.49884714285714316, 0.9001599999999996],
#        [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.44835904761904793, 0.47232476190476225],
#        [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.45494714285714327],
#        [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
#        ]

    data = [go.Contour(z=mz, x=mx, y=mx)]

    py.plot(data)
Ejemplo n.º 9
0
    def render(self, time, height):

        df = self._get_df(time, height)
        trace = go.Contour(
            z=df.values,
            colorbar=go.ColorBar(title='Pascals'),
        )
        data = [trace]

        layout = go.Layout(
            title='Pressure for t={} and Altitude (z={}): {:.1f} km'.format(
                str(time).lstrip('0'), height, height * 0.2),
            xaxis=dict(title='Longitude'),
            yaxis=dict(title='Latitude'),
        )

        fig = go.Figure(data=data, layout=layout)
        plotly.offline.iplot(fig)
Ejemplo n.º 10
0
def plotContourScatter(grid, path, name='contour-scatter.html'):

    trace1 = go.Contour(z=grid, ncontours=30, showscale=True)

    trace2 = go.Scatter(x=path[:, 0],
                        y=path[:, 1],
                        mode='markers+lines',
                        name='steepest',
                        line=dict(color='black'))

    data = [trace1, trace2]

    layout = go.Layout(autosize=True,
                       yaxis=dict(scaleanchor="x", scaleratio=1))

    fig = go.Figure(data=data, layout=layout)

    py.plot(fig, filename=name, auto_open=True)
Ejemplo n.º 11
0
    def plot_contour(self, z, prop, level):
        xv = np.array(self.geology['grid']['x'])
        yv = np.array(self.geology['grid']['y'])
        zv = np.array(self.geology['grid'][z])
        propv = np.array(self.geology['grid'][prop])

        xvc = xv[(zv >= level) & (zv < level + self.header['z_grid'])]
        yvc = yv[(zv >= level) & (zv < level + self.header['z_grid'])]
        propvc = propv[(zv >= level) & (zv < level + self.header['z_grid'])]

        contour = go.Contour(x=xvc, y=yvc, z=propvc, colorscale='Viridis')

        obs = go.Scatter(x=self.wells['obs']['surf_x'],
                         y=self.wells['obs']['surf_y'],
                         marker={
                             'color': 'purple',
                             'symbol': 17,
                             'size': 10
                         },
                         mode='markers',
                         name='obs')

        inj = go.Scatter(x=self.wells['inj']['surf_x'],
                         y=self.wells['inj']['surf_y'],
                         marker={
                             'color': 'red',
                             'symbol': 6,
                             'size': 10
                         },
                         mode='markers',
                         name='inj')

        prod = go.Scatter(x=self.wells['prod']['surf_x'],
                          y=self.wells['prod']['surf_y'],
                          marker={
                              'color': 'green',
                              'symbol': 28,
                              'size': 10
                          },
                          mode='markers',
                          name='prod')

        plot([contour, obs, inj, prod], filename='plot_contour')
Ejemplo n.º 12
0
 def createContour(self):
     val = self.nodes['val']
     contourMax = np.max(val)
     contourMin = np.min(val)
     contourSize = 0.1 * (contourMax - contourMin)
     coordinate = self.nodes['xy']
     val = self.nodes['val']
     data = go.Contour(
         x=coordinate[:, 0],
         y=coordinate[:, 1],
         z=val,
         # connectgaps=False,
         contours=dict(
             start=contourMin,
             end=contourMax,
             size=contourSize,
         ),
     )
     self.plotdata.append(data)
Ejemplo n.º 13
0
def interactive_plot(est, X0, X1, Y, x_label="X1", y_label="X2", title="decision_boundary",
                     file_name='decision_iplot', height=10, width=10):
    figure = tools.make_subplots(rows=1, cols=1, print_grid=False)

    X_, xx, yy = _create_meshgrid(X0, X1)
    Z = est.predict(X_).reshape(xx.shape)

    # generate the contour
    trace1 = go.Contour(x=xx[0], y=yy[:, 1], z=Z, colorscale='Viridis', opacity=0.2, showscale=False)

    # Scatter plot is generated using the original specified data points
    trace2 = go.Scatter(x=X0, y=X1, showlegend=False, mode='markers',
                        marker=dict(color=Y, line=dict(color='black', width=1),
                                    colorscale='Viridis', showscale=True))

    figure.append_trace(trace1, 1, 1)
    figure.append_trace(trace2, 1, 1)

    layout = go.Layout(
        xaxis=dict(autorange=True,
                   showgrid=False,
                   zeroline=False,
                   showline=True,
                   ticks='',
                   showticklabels=True,
                   title=x_label),
        yaxis=dict(autorange=True,
                   showgrid=False,
                   zeroline=False,
                   showline=True,
                   ticks='',
                   showticklabels=True,
                   title=y_label),
        plot_bgcolor='rgba(0, 0, 0, 0)',
        width=width,
        height=height,
        title=title
    )

    figure.update(layout=layout)
    py.iplot(figure, filename=file_name)
    return py, figure
Ejemplo n.º 14
0
    def build_prediction_figure(self, figure_layout=go.Layout(), step_size=0.01):
        """
        Building the classifier prediction figure.
        :param figure_layout: figure layout - plot.ly Layout object.
        :param step_size: Plot resolution.
        """

        data = list()

        x_min, x_max = self.dataset['data'][:, 0].min() - 1, self.dataset['data'][:, 0].max() + 1
        y_min, y_max = self.dataset['data'][:, 1].min() - 1, self.dataset['data'][:, 1].max() + 1

        x = np.arange(x_min, x_max, step_size)
        y = np.arange(y_min, y_max, step_size)
        x_mesh, y_mesh = np.meshgrid(x, y)

        z = self.trained_cluster.predict(np.column_stack((x_mesh.ravel(), y_mesh.ravel())))

        z = z.reshape(x_mesh.shape)

        data.append(go.Contour(x=x, y=y, z=z,
                               showscale=False,
                               hoverinfo='skip',
                               colorscale='Viridis'))

        data.append(go.Scatter(x=self.dataset['data'][:, 0],
                               y=self.dataset['data'][:, 1],
                               text=[self.classes_names[i] for i in self.trained_cluster.predict(self.dataset['data'])],
                               hoverinfo='text',
                               mode='markers',
                               marker=dict(color=self.trained_cluster.predict(self.dataset['data']),
                                           showscale=False,
                                           colorscale='Reds',
                                           line=dict(color='black', width=1))))

        if 'feature_names' in self.dataset.keys():
            figure_layout['xaxis'].update({'title': self.dataset['feature_names'][0]})
            figure_layout['yaxis'].update({'title': self.dataset['feature_names'][1]})

        self.prediction_figure = go.Figure(data=data, layout=figure_layout)
Ejemplo n.º 15
0
def generate_contour(data, tag):
    """ this plot gets regenerated far too many times """
    logging.debug("Generating a unique contour plot...")
    times = data['Time'].values
    radii = np.linspace(0, 1, get_data.NUM_GRID_POINTS)
    heights = data.loc[:,
                       get_data.
                       profile_column_names(tag[:-1], get_data.NUM_GRID_POINTS
                                            )].transpose().values
    return go.Contour(
        x=times,
        y=-radii,
        z=heights,
        showscale=False,
        showlegend=False,
        hoverinfo='text',
        text=[[
            u"t:  {:.3f}<br>ρ: {:.3f}<br>{}: {}".format(
                times[j], radii[i], tag[0], si_format(z))
            for j, z in enumerate(row)
        ] for i, row in enumerate(heights)],
    )  # I must cast to dict so that it serialises properly
Ejemplo n.º 16
0
def plotIsoForest(transformed, description, classifier):
    # get boundaries
    fig = tools.make_subplots()
    xmax = pd.DataFrame(transformed).describe()[0]['max']
    xmin = pd.DataFrame(transformed).describe()[0]['min']
    ymax = pd.DataFrame(transformed).describe()[1]['max']
    ymin = pd.DataFrame(transformed).describe()[1]['min']
    # plot the contour graph
    X = np.linspace(xmin - 5, xmax + 5, 500)
    Y = np.linspace(ymin - 5, ymax + 5, 500)
    xx, yy = np.meshgrid(X, Y)
    clf = classifier
    Z = clf.decision_function(np.c_[xx.ravel(), yy.ravel()])
    Z = Z.reshape(xx.shape)

    back = go.Contour(
        x=X,
        y=Y,
        z=Z,
        autocontour=True,
        #ncontours=7,
        contours=dict(showlines=False),
        showscale=False)
    #colorscale = matplotlib_to_plotly(plt.cm.Blues, 10))
    #X_train=transformed.copy()
    b = go.Scatter(x=transformed[:, 0],
                   y=transformed[:, 1],
                   showlegend=False,
                   text=listOfCountries.index,
                   mode='markers',
                   marker=dict(color='white',
                               line=dict(color='black', width=1)))

    fig.append_trace(back, 1, 1)
    fig.append_trace(b, 1, 1)
    #row+=1

    fig['layout'].update(height=900, hovermode='closest', hoverdistance=1)
    return fig
def loss_contour_plot(theta_1_series, theta_2_series, loss_function,  x, y, flip_axes = False):
    """    
    The function takes the following as argument:
        theta_1: a list or array of theta_1 value
        theta_2: a list or array of theta_2 value
        loss_function
        x: the original x input
        y: the original y output
    """
    t1_s = np.linspace(np.min(theta_1_series) - 0.1, np.max(theta_1_series) + 0.1)
    t2_s = np.linspace(np.min(theta_2_series) - 0.1, np.max(theta_2_series) + 0.1)

    x_s, y_s = np.meshgrid(t1_s, t2_s)
    data = np.stack([x_s.flatten(), y_s.flatten()]).T
    ls = []
    for t1, t2 in data:
        l = loss_function(t1, t2, x, y)
        ls.append(l)
    z = np.array(ls).reshape(50, 50)

    if flip_axes:
        z = z.transpose()

    if not flip_axes:
        contour_x = t1_s
        contour_y = t2_s
    else:
        contour_x = t2_s
        contour_y = t1_s        

    lr_loss_contours = go.Contour(x=contour_x, 
                                  y=contour_y, 
                                  z=z, 
                                  colorscale='Viridis')
    
    contour_fig = go.Figure(data=[lr_loss_contours])
    contour_fig['layout']['yaxis']['autorange'] = "reversed"

    plotly.offline.iplot(contour_fig)
Ejemplo n.º 18
0
    def _plot_cut(fig, idx, pos, decode_points_func, xmax, ymax, resolution):
        """ plot one cross section pos (3, N) """
        # evaluate points in serial
        field_input = torch.tensor(pos.T, dtype=torch.float).cuda()
        values = decode_points_func(field_input).flatten()
        if isinstance(values, torch.Tensor):
            values = values.cpu().numpy()
        values = values.reshape(resolution, resolution)
        contour_dict = dict(
            autocontour=False,
            colorscale='RdBu',
            contours=dict(
                start=-0.2 + thres,
                end=0.2 + thres,
                size=0.05,
                showlabels=True,  # show labels on contours
                labelfont=dict(  # label font properties
                    size=12,
                    color='white',
                )),
        )
        r_idx = idx // 3

        fig.add_trace(
            go.Contour(x=np.linspace(-xmax, xmax, resolution),
                       y=np.linspace(-ymax, ymax, resolution),
                       z=values,
                       **contour_dict),
            col=idx % 3 + 1,
            row=r_idx + 1  # 1-idx
        )

        fig.update_xaxes(
            range=[-xmax, xmax],  # sets the range of xaxis
            constrain=
            "range",  # meanwhile compresses the xaxis by decreasing its "domain"
            col=idx % 3 + 1,
            row=r_idx + 1)
        fig.update_yaxes(range=[-ymax, ymax], col=idx % 3 + 1, row=r_idx + 1)
Ejemplo n.º 19
0
def make_flowfield(n_clicks,airfoil_data,var,show_points):
    # Parse data
    design_vec = airfoil_data['design-vec']
    airfoil_x  = airfoil_data['airfoil-x']
    airfoil_y  = airfoil_data['airfoil-y']
    airfoil_x  = np.hstack([airfoil_x[-1],airfoil_x])
    airfoil_y  = np.hstack([airfoil_y[-1],airfoil_y])

    # Setup fig
    layout={'clickmode':'event+select','margin':dict(t=0,r=0,l=0,b=0,pad=0),'showlegend':False,"xaxis": {"title": 'x/C'}, "yaxis": {"title": 'y/C'},
            'paper_bgcolor':'white','plot_bgcolor':'white','autosize':False}
    fig = go.Figure(layout=layout)

    # Plot airfoil
    fig.add_trace(go.Scatter(x=airfoil_x,y=airfoil_y,mode='lines',name='Deformed',line_width=8,line_color='blue',fill='tozeroy',fillcolor='rgba(0, 0, 255, 1.0)'))

    # Contour plot (if button has just been pressed)
    changed_id = [p['prop_id'] for p in dash.callback_context.triggered][0]
    if 'compute-flowfield' in changed_id:
        ypred = compute_flowfield(design_vec,var)
        fig.add_trace(go.Contour(x=x,y=y,z=ypred.reshape(len(x),len(y)),transpose=True, colorbar=dict(len=0.7),#title=dict(text=var_name[var],side='right')), colorbar title removed for now as doesn't work with latex. (Plotly issue #2231)
            contours=dict(
            start=np.nanmin(ypred),
            end=np.nanmax(ypred),
            size=(np.nanmax(ypred)-np.nanmin(ypred))/20,
            )

        ))

    if show_points: 
        xx,yy = np.meshgrid(x,y,indexing='ij')
        xx,yy = airfoil_mask(xx,yy,airfoil_x,airfoil_y)
        fig.add_trace(go.Scatter(x=xx.flatten(),y=yy.flatten(),mode='markers',marker_color='black',opacity=0.4,marker_symbol='circle-open',marker_size=6,marker_line_width=2))

    #fig.update_xaxes(range=[-1.12844, 1.830583])
    fig.update_xaxes(range=[-0.8, 1.6], showgrid=False, zeroline=False, visible=False)
    fig.update_yaxes(range=[-0.5822106,0.5001755],scaleanchor = "x", scaleratio = 1, showgrid=False, zeroline=False, visible=False)

    return fig, None
def func(custom_data_storage):
    data = json.loads(custom_data_storage)

    trace0 = go.Contour(
        x=np.linspace(0, 10, 200),
        y=np.linspace(0, 10, 200),
        z=np.ones(shape=(200, 200)),
        showscale=False,
        hoverinfo='none',
        contours=dict(coloring='lines'),
    )
    trace1 = go.Scatter(x=data['train_X'],
                        y=data['train_y'],
                        mode='markers',
                        name='Training')
    trace2 = go.Scatter(x=data['test_X'],
                        y=data['test_y'],
                        mode='markers',
                        name='Training')

    data = [trace0, trace1, trace2]
    figure = go.Figure(data=data)
    return figure
Ejemplo n.º 21
0
    def build_decision_regions(self, **data):
        df = data['df_regions']

        x_min, y_min = 1.2 * list(df.min())[0] - 10, 1.2 * list(
            df.min())[1] - 10
        x_max, y_max = 1.2 * list(df.max())[0] + 10, 1.2 * list(
            df.max())[1] + 10
        x = np.arange(x_min, x_max, 0.1)
        y = np.arange(y_min, y_max, 0.1)
        xx, yy = np.meshgrid(x, y)
        z = data['classifier'].predict(np.c_[xx.ravel(), yy.ravel()])
        unique_labels = list(set(data['labels']))
        mapper = dict(
            zip(unique_labels, list(np.linspace(0, 1, len(unique_labels)))))
        z = np.array([mapper[el] for el in z])
        z = z.reshape(xx.shape)

        plot_input = dict()
        plot_input['x'] = x
        plot_input['y'] = y
        plot_input['z'] = z
        step_size = 1 / (len(unique_labels) - 1)
        plot_input['contours'] = {
            'start': 0 - 0.5 * step_size,
            'size': step_size,
            'end': 1 + 0.5 * step_size
        }

        layout = dict()
        layout['title'] = data['title']

        return {
            'data':
            [go.Contour(dict(cnf.GUI.DECISION_REGIONS_STYLE, **plot_input))],
            'layout':
            go.Layout(dict(cnf.GUI.GRAPH_LAYOUT, **layout))
        }
Ejemplo n.º 22
0
    def buildTrace(self):
        '''
        build the final trace calling the go.xxx plotly method
        this method here is the one performing the real job

        From the initial object created (e.g. p = Plot(plot_type, plot_properties,
        layout_properties)) this methods checks the plot_type and elaborates the
        plot_properties dictionary passed

        Console usage:
        # create the initial object
        p = Plot(plot_type, plot_properties, layout_properties)
        # call the method
        p.buildTrace()

        Returns the final Plot Trace (final Plot object, AKA go.xxx plot type)
        '''

        if self.plot_type == 'scatter':

            self.trace = [go.Scatter(
                x=self.plot_properties['x'],
                y=self.plot_properties['y'],
                mode=self.plot_properties['marker'],
                name=self.plot_properties['name'],
                ids=self.plot_properties['featureIds'],
                customdata=self.plot_properties['custom'],
                text=self.plot_properties['additional_hover_text'],
                hoverinfo=self.plot_properties['hover_text'],
                marker=dict(
                    color=self.plot_properties['in_color'],
                    colorscale=self.plot_properties['colorscale_in'],
                    showscale=self.plot_properties['show_colorscale_legend'],
                    reversescale=self.plot_properties['invert_color_scale'],
                    colorbar=dict(
                        len=0.8
                    ),
                    size=self.plot_properties['marker_size'],
                    symbol=self.plot_properties['marker_symbol'],
                    line=dict(
                        color=self.plot_properties['out_color'],
                        width=self.plot_properties['marker_width']
                    )
                ),
                line=dict(
                    width=self.plot_properties['marker_width'],
                    dash=self.plot_properties['line_dash']
                ),
                opacity=self.plot_properties['opacity']
            )]

        elif self.plot_type == 'box':


            # flip the variables according to the box orientation
            if self.plot_properties['box_orientation'] == 'h':
                self.plot_properties['x'], self.plot_properties['y'] = self.plot_properties['y'], self.plot_properties['x']

            self.trace = [go.Box(
                x=self.plot_properties['x'],
                y=self.plot_properties['y'],
                name=self.plot_properties['name'],
                customdata=self.plot_properties['custom'],
                boxmean=self.plot_properties['box_stat'],
                orientation=self.plot_properties['box_orientation'],
                boxpoints=self.plot_properties['box_outliers'],
                fillcolor=self.plot_properties['in_color'],
                line=dict(
                    color=self.plot_properties['out_color'],
                    width=self.plot_properties['marker_width']
                ),
                opacity=self.plot_properties['opacity']
            )]

        elif self.plot_type == 'bar':

            if self.plot_properties['box_orientation'] == 'h':
                self.plot_properties['x'], self.plot_properties['y'] = self.plot_properties['y'], self.plot_properties['x']

            self.trace = [go.Bar(
                x=self.plot_properties['x'],
                y=self.plot_properties['y'],
                name=self.plot_properties['name'],
                ids=self.plot_properties['featureBox'],
                customdata=self.plot_properties['custom'],
                orientation=self.plot_properties['box_orientation'],
                marker=dict(
                    color=self.plot_properties['in_color'],
                    colorscale=self.plot_properties['colorscale_in'],
                    showscale=self.plot_properties['show_colorscale_legend'],
                    reversescale=self.plot_properties['invert_color_scale'],
                    colorbar=dict(
                        len=0.8
                    ),
                    line=dict(
                        color=self.plot_properties['out_color'],
                        width=self.plot_properties['marker_width']
                    )
                ),
                opacity=self.plot_properties['opacity']
            )]

        elif self.plot_type == 'histogram':

            self.trace = [go.Histogram(
                x=self.plot_properties['x'],
                y=self.plot_properties['x'],
                name=self.plot_properties['name'],
                orientation=self.plot_properties['box_orientation'],
                nbinsx=self.plot_properties['bins'],
                nbinsy=self.plot_properties['bins'],
                marker=dict(
                    color=self.plot_properties['in_color'],
                    line=dict(
                        color=self.plot_properties['out_color'],
                        width=self.plot_properties['marker_width']
                    )
                ),
                histnorm=self.plot_properties['normalization'],
                opacity=self.plot_properties['opacity'],
                cumulative=dict(
                    enabled=self.plot_properties['cumulative'],
                    direction=self.plot_properties['invert_hist']
                    )
            )]

        elif self.plot_type == 'pie':

            self.trace = [go.Pie(
                labels=self.plot_properties['x'],
                values=self.plot_properties['y'],
                name=self.plot_properties['custom'][0],
            )]

        elif self.plot_type == '2dhistogram':

            self.trace = [go.Histogram2d(
                x=self.plot_properties['x'],
                y=self.plot_properties['y'],
                colorscale=self.plot_properties['color_scale']
            )]

        elif self.plot_type == 'polar':

            self.trace = [go.Scatterpolar(
                r=self.plot_properties['y'],
                theta=self.plot_properties['x'],
                mode=self.plot_properties['marker'],
                name=self.plot_properties['y_name'],
                marker=dict(
                    color=self.plot_properties['in_color'],
                    size=self.plot_properties['marker_size'],
                    symbol=self.plot_properties['marker_symbol'],
                    line=dict(
                        color=self.plot_properties['out_color'],
                        width=self.plot_properties['marker_width']
                    )
                ),
                line=dict(
                    color=self.plot_properties['in_color'],
                    width=self.plot_properties['marker_width'],
                    dash=self.plot_properties['line_dash']
                ),
                opacity=self.plot_properties['opacity'],
            )]

        elif self.plot_type == 'ternary':

            # prepare the hover text to display if the additional combobox is empty or not
            # this setting is necessary to overwrite the standard hovering labels
            if self.plot_properties['additional_hover_text'] == []:
                text = [self.plot_properties['x_name'] + ': {}'.format(self.plot_properties['x'][k]) + '<br>{}: {}'.format(self.plot_properties['y_name'], self.plot_properties['y'][k]) + '<br>{}: {}'.format(self.plot_properties['z_name'], self.plot_properties['z'][k]) for k in range(len(self.plot_properties['x']))]
            else:
                text = [self.plot_properties['x_name'] + ': {}'.format(self.plot_properties['x'][k]) + '<br>{}: {}'.format(self.plot_properties['y_name'], self.plot_properties['y'][k]) + '<br>{}: {}'.format(self.plot_properties['z_name'], self.plot_properties['z'][k]) + '<br>{}'.format(self.plot_properties['additional_hover_text'][k]) for k in range(len(self.plot_properties['x']))]

            self.trace = [go.Scatterternary(
                a=self.plot_properties['x'],
                b=self.plot_properties['y'],
                c=self.plot_properties['z'],
                name=self.plot_properties['x_name'] + ' + ' + self.plot_properties['y_name'] + ' + ' + self.plot_properties['z_name'],
                hoverinfo='text',
                text=text,
                mode='markers',
                marker=dict(
                    color=self.plot_properties['in_color'],
                    colorscale=self.plot_properties['colorscale_in'],
                    showscale=self.plot_properties['show_colorscale_legend'],
                    reversescale=self.plot_properties['invert_color_scale'],
                    colorbar=dict(
                        len=0.8
                    ),
                    size=self.plot_properties['marker_size'],
                    symbol=self.plot_properties['marker_symbol'],
                    line=dict(
                        color=self.plot_properties['out_color'],
                        width=self.plot_properties['marker_width']
                    )
                ),
                opacity=self.plot_properties['opacity']
            )]

        elif self.plot_type == 'contour':

            self.trace = [go.Contour(
                z=[self.plot_properties['x'], self.plot_properties['y']],
                contours=dict(
                    coloring=self.plot_properties['cont_type'],
                    showlines=self.plot_properties['show_lines']
                ),
                colorscale=self.plot_properties['color_scale'],
                opacity=self.plot_properties['opacity']
            )]

        elif self.plot_type == 'violin':

            # flip the variables according to the box orientation
            if self.plot_properties['box_orientation'] == 'h':
                self.plot_properties['x'], self.plot_properties['y'] = self.plot_properties['y'], self.plot_properties['x']

            self.trace = [go.Violin(
                x=self.plot_properties['x'],
                y=self.plot_properties['y'],
                name=self.plot_properties['name'],
                customdata=self.plot_properties['custom'],
                orientation=self.plot_properties['box_orientation'],
                points=self.plot_properties['box_outliers'],
                fillcolor=self.plot_properties['in_color'],
                line=dict(
                    color=self.plot_properties['out_color'],
                    width=self.plot_properties['marker_width']
                ),
                opacity=self.plot_properties['opacity'],
                meanline=dict(
                    visible=self.plot_properties['show_mean_line']
                ),
                side=self.plot_properties['violin_side']
                )]

        return self.trace
Ejemplo n.º 23
0
                    showlegend=False)
SVs = svm.support_vectors_
support_vectors = go.Scatter(x=SVs[:, 0],
                             y=SVs[:, 1],
                             mode='markers',
                             marker=dict(size=15,
                                         color='black',
                                         opacity=0.1,
                                         colorscale=points_colorscale),
                             line=dict(dash='solid'),
                             showlegend=False)

decision_surface = go.Contour(x=x_vis_0_range,
                              y=x_vis_1_range,
                              z=YY_vis,
                              contours_coloring='lines',
                              line_width=2,
                              contours=dict(start=0, end=0, size=1),
                              colorscale=decision_colorscale,
                              showscale=False)

margins = go.Contour(x=x_vis_0_range,
                     y=x_vis_1_range,
                     z=YY_vis,
                     contours_coloring='lines',
                     line_width=2,
                     contours=dict(start=-1, end=1, size=2),
                     line=dict(dash='dash'),
                     colorscale=decision_colorscale,
                     showscale=False)

fig2 = go.Figure(data=[margins, decision_surface, support_vectors, points],
Ejemplo n.º 24
0
        style={
            'textAlign': 'center',
            'color': colors['text']
        }),
    dcc.Graph(id='produced-wind-power',
              figure={
                  'data': fig_data,
                  'layout': {
                      'title': 'Wind power produced (MWh)',
                      'plot_bgcolor': colors['background'],
                      'paper_bgcolor': colors['background'],
                      'font': {
                          'color': colors['text']
                      }
                  }
              }),
    dcc.Graph(figure=go.Figure(data=data, layout=layout)),
    dcc.Graph(figure=go.Figure(data=[
        go.Contour(z=matrix_data,
                   x=lons_rotated[0, :],
                   y=lats[:, 0],
                   opacity=0.8,
                   contours={'coloring': 'fill'}),
    ],
                               layout=layout))
],
                      style={'backgroundColor': colors['background']})

if __name__ == '__main__':
    app.run_server(debug=True)
Ejemplo n.º 25
0
import plotly.graph_objs as go
import matplotlib.pyplot as plt
import wandb

wandb.init()
contour = go.Figure(
    data=go.Contour(
        z=[[10, 10.625, 12.5, 15.625, 20], [5.625, 6.25, 8.125, 11.25, 15.625],
           [2.5, 3.125, 5., 8.125, 12.5], [0.625, 1.25, 3.125, 6.25, 10.625],
           [0, 0.625, 2.5, 5.625, 10]]),
    layout=go.Layout(title=go.layout.Title(text="A Bar Chart")))
scatter = go.Figure(
    data=go.Scatter(x=[0, 1, 2]),
    layout=go.Layout(title=go.layout.Title(text="A Bar Chart")))

plt.plot([1, 2, 3, 4])
plt.ylabel('some interesting numbers')

wandb.log({'contour': contour, 'scatter': scatter, 'mpl': plt})
Ejemplo n.º 26
0
    def plotly_hexbin(self):
        """plot_hexbin, but for plotly. it's annoying that we have to have sub-subplots"""
        fig = go.Figure()
        cols = self.plots_per_row if self.numplots > self.plots_per_row else self.numplots
        rows = np.ceil(self.numplots / float(cols)).astype(int)
        fig['layout'].update(title=self.plot_title)
        domainWidth = .9 / cols
        domainHeight = .9 / rows
        bufferHeight = 0.0
        if rows > 1:
            bufferHeight = 0.1 / (rows - 1)
        else:
            domainHeight = 1.0
        bufferWidth = 0.0
        if cols > 1:
            bufferWidth = 0.1 / (cols - 1)
        else:
            domainWidth = 1.0
        subHeight = domainHeight / float(self.numlines)
        if self.per_group:
            sideLabels = self.hm.matrix.sample_labels
        else:
            sideLabels = self.hm.matrix.group_labels

        data = []
        annos = []
        vmin = np.inf
        vmax = -np.inf
        for i in range(self.numplots):
            row = rows - i / self.plots_per_row - 1
            col = i % self.plots_per_row

            if self.per_group:
                title = self.hm.matrix.group_labels[i]
            else:
                title = self.hm.matrix.sample_labels[i]

            base = row * (domainHeight + bufferHeight)
            domain = [base, base + domainHeight]
            titleY = base + domainHeight
            base = col * (domainWidth + bufferWidth)
            domain = [base, base + domainWidth]
            titleX = base + 0.5 * domainWidth
            xanchor = 'x{}'.format(i + 1)
            fig['layout']['xaxis{}'.format(i + 1)] = dict(domain=domain)
            annos.append({
                'yanchor': 'bottom',
                'xref': 'paper',
                'xanchor': 'center',
                'yref': 'paper',
                'text': title,
                'y': titleY,
                'x': titleX,
                'font': {
                    'size': 16
                },
                'showarrow': False
            })

            # set yMin/yMax
            yMin = np.inf
            yMax = -np.inf
            for j in range(self.numlines):
                # get the max and min
                if self.per_group:
                    _row, _col = i, j
                else:
                    _row, _col = j, i

                ma = self.hm.matrix.get_matrix(_row, _col)['matrix']
                if np.min(ma) < yMin:
                    yMin = np.min(ma)
                if np.max(ma) > yMax:
                    yMax = np.max(ma)
            if self.y_min[i % len(self.y_min)] is not None:
                yMin = self.y_min[i % len(self.y_min)]
            if self.y_max[i % len(self.y_max)] is not None:
                yMax = self.y_max[i % len(self.y_max)]

            for j in range(self.numlines):
                if self.per_group:
                    _row, _col = i, j
                else:
                    _row, _col = j, i
                foo = i * self.numlines + j + 1
                yanchor = 'y{}'.format(foo)
                base = row * (domainHeight + bufferHeight) + j * subHeight
                domain = [base, base + subHeight]
                fig['layout']['yaxis{}'.format(foo)] = {
                    'domain': domain,
                    'title': self.y_axis_label,
                    'anchor': xanchor,
                    'range': [yMin, yMax]
                }
                if j == 0:
                    _ = "xaxis{}".format(xanchor[1:])
                    fig['layout'][_].update(anchor='y{}'.format(foo))
                if col == 0:
                    titleY = base + 0.5 * subHeight
                    annos.append({
                        'yanchor': 'middle',
                        'xref': 'paper',
                        'xanchor': 'left',
                        'yref': 'paper',
                        'text': sideLabels[j],
                        'y': titleY,
                        'x': -0.03,
                        'font': {
                            'size': 16
                        },
                        'showarrow': False,
                        'textangle': -90
                    })

                sub_matrix = self.hm.matrix.get_matrix(_row, _col)
                ma = self.hm.matrix.get_matrix(_row, _col)['matrix']

                fig['layout']['xaxis{}'.format(i + 1)].update(
                    range=[0, ma.shape[1]])

                if self.per_group:
                    label = sub_matrix['sample']
                else:
                    label = sub_matrix['group']

                # Manually compute the 2D histogram with 100x100 bins
                x_values = np.tile(np.arange(ma.shape[1]), (ma.shape[0], 1))
                z, xe, ye = np.histogram2d(x_values.flatten(),
                                           ma.flatten(),
                                           bins=100,
                                           range=[[0, ma.shape[1]],
                                                  [yMin, yMax]])

                _vmin = np.min(z)
                _vmax = np.max(z)
                if _vmin < vmin:
                    vmin = _vmin
                if _vmax > vmax:
                    vmax = _vmax

                trace = go.Contour(z=z.T,
                                   x=xe,
                                   y=ye,
                                   xaxis=xanchor,
                                   yaxis=yanchor,
                                   name=label,
                                   connectgaps=False)
                data.append(trace)

            # Assume the bounds for the last graph are correct
            totalWidth = ma.shape[1]
            xticks, xtickslabel = self.getTicks(i)
            if np.ceil(max(xticks)) != float(totalWidth):
                tickscale = float(totalWidth) / max(xticks)
                xticks_use = [x * tickscale for x in xticks]
            else:
                xticks_use = xticks
            xticks_use = [np.ceil(x) for x in xticks_use]
            fig['layout']['xaxis{}'.format(i + 1)].update(
                tickmode='array',
                tickvals=xticks_use,
                ticktext=xtickslabel,
                tickangle=self.label_rotation)

        for trace in data:
            trace.update(zmin=vmin, zmax=vmax)

        fig['data'] = data
        fig['layout']['annotations'] = annos
        py.plot(fig, filename=self.out_file_name, auto_open=False)
Ejemplo n.º 27
0
    lat_rad = math.radians(lat_deg)
    xtile =(lon_deg + 180.0) / 360.0
    ytile =(1.0 - math.log(math.tan(lat_rad) + (1 / math.cos(lat_rad))) / math.pi) / 2.0
    return [xtile, ytile]

parsed_trips = parse_trips(trips)
cleaned_trips = float_values(parsed_trips)

#40.702030, -74.019704
#40.807611, -73.929674
xminll=40.699984
xmaxll=40.807611
yminll=-74.019704
ymaxll=-73.953073

numpoints=10 #this is the number of x points and y points, so total sample points is this squared
xlist=list(np.linspace(xmin,xmax,numpoints))
ylist=list(np.linspace(ymin,ymax,numpoints))

xx,yy = np.meshgrid(xlist, ylist)
vectorz=np.vectorize(zvalue)
zgrid=vectorz(xx,yy)

mmin=deg2num(xminll,yminll)
mmax=deg2num(xmaxll,ymaxll)

plotx=list(np.linspace(mmin[0],mmax[0],numpoints))
ploty=list(np.linspace(mmin[1],mmax[1],numpoints))
data=[go.Contour(x=plotx,y=ploty,z=zgrid)]
plotly.offline.iplot(data)
def update_figure(cont_clicks, stop_clicks, selected_data):
    
    ctx = dash.callback_context
    #print('Trig : ' + str( ctx.triggered) )
    #print("Start : " + str(start_clicks) + " Stop : "+ str(stop_clicks) + " Cont : " + str(cont_clicks))

    residual, mask = imcl.get_residual_and_mask()

    if ctx.triggered[0]['prop_id'].count('selectedData')>0:
        if selected_data != None:
            if 'range' in selected_data.keys() :
                #print(selected_data['range'])
                imcl.update_mask( selected_data['range'] )
                residual,mask = imcl.get_residual_and_mask()
            else:
                print("Only box region selection is currently supported")

    if ctx.triggered[0]['prop_id'].count('button')>0:
    
        ## Only once at the beginning
#        if start_clicks==1 and cont_clicks==None and stop_clicks==None and imcl.get_stopcode()==0:
#            imcl.make_observed_image()
#            residual, mask = imcl.get_residual_and_mask()

        ## Until you stop, or the stopcode goes to 1
        if stop_clicks==None and cont_clicks!=None and imcl.get_stopcode()==0:
            imcl.run_deconvolver()
            residual, mask = imcl.get_residual_and_mask()
            
        if stop_clicks==1 or  imcl.get_stopcode()==1:
            imcl.run_restore()


    traces=[]
    traces.append( go.Scatter(y=[None]) )
    traces.append( go.Heatmap(z=np.transpose(residual), 
                              showscale=False,
                              colorscale='Blackbody') )
    traces.append( go.Contour(z=np.transpose(mask), 
                              contours_coloring='lines',
                              line_width=4, 
                              showscale=False,
                              colorscale='Jet',
                              contours=dict(start=0.1,end=1.1,size=2)
                          ))

    iters, peaks, peaks_in_mask, majcycle = imcl.get_iter_plot()

    traces_plot=[]
    traces_plot.append( go.Scatter(x=iters, y=peaks, 
                                   mode='lines+markers', 
                                   name='Full Image' ))
    traces_plot.append( go.Scatter(x=iters, y=peaks_in_mask, 
                                   mode='lines+markers', 
                                   name='Within Mask' ))
    for it in majcycle:
        showlegend = False
        if it==majcycle[0]:
            showlegend=True
        traces_plot.append( go.Scatter(x=[it,it], y=[0, peaks[0]], 
                                       mode='lines' ,
                                       name='Major cycles',
                                       line=dict(color='grey',dash='dash'),
                                       showlegend=showlegend) )
    
    return [
        {
            'data': traces,
            'layout': go.Layout(
                xaxis={'title': 'RA (pix)'},
                yaxis={'title': 'DEC (pix)'},
                title="RESIDUAL IMAGE WITH MASK",
                width = 500, height = 500,
                autosize = True,
                dragmode = 'select',
                hovermode=False
            )} ,
        {
            'data': traces_plot,
            'layout': go.Layout(
                xaxis={'title': 'Iteration Count', 'range':[-0.5,imcl.get_niter()]},
                yaxis={'title': 'Peak Residual'},
                title="Convergence Plot : Peak Residual vs Iteration Number",
                width = 600, height = 500,
                autosize = True
            )} 
    ]
Ejemplo n.º 29
0
Archivo: app.py Proyecto: bgeszti/ML
def update_figure(selected,year, aggregation, depth_range):

    # select temperature if no measurement is selected
    if len(selected) == 0:
        selected = ['Temperature']

    # filter for one or more year from the measurements
    if year[0] != year[1]:
        tdf = df1[(df1['year'] >= year[0]) & (df1['year'] <= year[1])]
    else :
        tdf = df1[df1['year'] == year[0]]

    # filter the selected depth range if there is a range selected
    if depth_range[0] != depth_range[1]:
        tdf = tdf[(tdf['Depth MLW'] >= unique_depths[depth_range[0]]) & (tdf['Depth MLW'] <= unique_depths[depth_range[1]])]
    else :
        tdf = tdf

    # aggregate the measurements and get rid of double indexing
    depth_data = tdf
    depth_data.index = depth_data['TimeStamp']
    depth_data = depth_data.groupby(['Depth MLW',pd.Grouper(freq=aggregation)]).mean()
    depth_data_reset = depth_data.reset_index()
    depth_data_reset.columns = [
        'Depth MLW', 
        'TimeStamp', 
        'Temperature', 
        'Salinity',
        'Chlorophyll',
        'Oxygen.Electrode',
        'Oxygen.Saturation',
        'Calculated.Oxygen',
        'Optical.Backscatter',
        'Calculated.SPM',
        'Sigma.t',
        'Station.Number',
        'year'
    ]
    
    # make cotour plot
    depths = plotly.subplots.make_subplots(
        rows=len(selected),
        cols=1,
        shared_xaxes=True, 
        shared_yaxes=False,
        vertical_spacing=0.1
    )
    depth_traces = []
    colors=[colors1,colors2]

    for i in range(len(selected)):
        depths.update_yaxes(title_text=selected[i], row=i+1, col=1)
        depth_traces.append(go.Contour(
            z=depth_data_reset[selected[i]],
            y=depth_data_reset['Depth MLW'],
            x=depth_data_reset['TimeStamp'], 
            showscale=False,
            contours_coloring='heatmap',
            connectgaps=True,colorscale=colors[i]
        ))
        depths.append_trace(depth_traces[i], i+1, 1)

    # reversed y axis for depth data
    depths.update_yaxes(autorange="reversed")
    
    depths.update_layout(
        margin=dict(l=20, r=20, t=30, b=20),
        paper_bgcolor='#E5ECF6'
    )

    # return with contour plot
    return [depths]
Ejemplo n.º 30
0
    def get_figure(pourbaix_diagram,
                   heatmap_entry=None,
                   heatmap_as_contour=True,
                   show_labels=True):
        """
        Static method for getting plotly figure from a pourbaix diagram

        Args:
            pourbaix_diagram (PourbaixDiagram): pourbaix diagram to plot
            heatmap_entry (PourbaixEntry): id for the heatmap generation
            heatmap_as_contour (bool): if True, display contours, if False heatmap as grid

        Returns:
            (dict) figure layout

        """
        # TODO: fix mpid problem.  Can't attach from mpid without it being a structure.
        data = []

        # Get data for heatmap
        if heatmap_entry is not None:
            ph_range = np.arange(-2, 16.001, 0.1)
            v_range = np.arange(-2, 4.001, 0.1)
            ph_mesh, v_mesh = np.meshgrid(ph_range, v_range)
            decomposition_e = pourbaix_diagram.get_decomposition_energy(
                heatmap_entry, ph_mesh, v_mesh)

            # Generate hoverinfo
            hovertexts = []
            for ph_val, v_val, de_val in zip(ph_mesh.ravel(), v_mesh.ravel(),
                                             decomposition_e.ravel()):
                hovertext = [
                    "∆G<sub>pbx</sub>={:.2f}".format(de_val),
                    "ph={:.2f}".format(ph_val),
                    "V={:.2f}".format(v_val),
                ]
                hovertext = "<br>".join(hovertext)
                hovertexts.append(hovertext)
            hovertexts = np.reshape(hovertexts, list(decomposition_e.shape))

            # Enforce decomposition limit energy
            decomposition_e = np.min(
                [decomposition_e,
                 np.ones(decomposition_e.shape)], axis=0)

            if not heatmap_as_contour:
                # Plotly needs a list here for validation
                hmap = go.Heatmap(
                    x=list(ph_range),
                    y=list(v_range),
                    z=decomposition_e,
                    text=hovertexts,
                    hoverinfo="text",
                    colorbar={
                        "title": "∆G<sub>pbx</sub> (eV/atom)",
                        "titleside": "right",
                    },
                    colorscale=PourbaixDiagramComponent.colorscale,
                    zmin=0,
                    zmax=1,
                )
                data.append(hmap)

            else:

                hmap = go.Contour(
                    z=decomposition_e,
                    x=list(ph_range),
                    y=list(v_range),
                    colorscale=PourbaixDiagramComponent.colorscale,  # or magma
                    zmin=0,
                    zmax=1,
                    connectgaps=True,
                    line_smoothing=0,
                    line_width=0,
                    contours_coloring="heatmap",
                    text=hovertexts,
                )
                data.insert(0, hmap)

        shapes = []
        xydata = []
        labels = []

        for entry, vertices in pourbaix_diagram._stable_domain_vertices.items(
        ):
            formula = entry.name
            clean_formula = PourbaixDiagramComponent.clean_formula(formula)

            # Generate annotation
            xydata.append(np.average(vertices, axis=0))
            labels.append(clean_formula)

            # Info on SVG paths: https://developer.mozilla.org/en-US/docs/Web/SVG/Tutorial/Paths
            # Move to first point
            path = "M {},{}".format(*vertices[0])
            # Draw lines to each other point
            path += "".join(
                ["L {},{}".format(*vertex) for vertex in vertices[1:]])
            # Close path
            path += "Z"

            # Note that the lines and fills are added separately
            # so that the lines but not the fills will show up on heatmap.
            # This may be condensable in the future if plotly adds a more
            # general z-ordering of objects

            # Fill with turquoise if solution
            if heatmap_entry is None:
                fillcolor = "White" if "Ion" in entry.phase_type else "PaleTurquoise"
                shape = go.layout.Shape(
                    type="path",
                    path=path,
                    fillcolor=fillcolor,
                    line_color=None,
                    layer="below",
                )
                shapes.append(shape)

            # Add lines separately so they show up on heatmap
            shape = go.layout.Shape(type="path",
                                    path=path,
                                    fillcolor=None,
                                    line_color="Black")
            shapes.append(shape)

        layout = PourbaixDiagramComponent.default_plot_style
        layout.update({"shapes": shapes})

        if show_labels:
            if len(pourbaix_diagram.pbx_elts) == 1:
                # Add annotations to layout
                annotations = [
                    {
                        "align": "center",
                        "font": {
                            "color": "#000000",
                            "size": 15.0
                        },
                        "opacity": 1,
                        "showarrow": False,
                        "text": label,
                        "x": x,
                        "xanchor": "center",
                        "yanchor": "auto",
                        # "xshift": -10,
                        # "yshift": -10,
                        "xref": "x",
                        "y": y,
                        "yref": "y",
                    } for (x, y), label in zip(xydata, labels)
                ]
                layout.update({"annotations": annotations})
            else:
                x, y = zip(*xydata)
                data.append(
                    go.Scatter(x=x,
                               y=y,
                               text=labels,
                               hoverinfo="text",
                               mode="markers"))

        figure = go.Figure(data=data, layout=layout)

        return figure