Example #1
0
def dr_cdl(df,
           m_title='分时数据K线图',
           ftg='tmp/tmp_plotly.html',
           m_tkAng=-20,
           m_dtick=5,
           m_y2k=3):
    fig = pyff.create_candlestick(df.open,
                                  df.high,
                                  df.low,
                                  df.close,
                                  dates=df.index)
    fig['layout'].update(
        title=m_title,
        xaxis=pygo.XAxis(
            autorange=True,
            gridcolor='rgb(180, 180, 180)',
            mirror='all',
            showgrid=True,
            showline=True,
            ticks='outside',
            tickangle=m_tkAng,
            dtick=m_dtick,
            type='category',
            categoryarray=df.index,
        ),
        yaxis=pygo.YAxis(
            autorange=True,
            gridcolor='rgb(180, 180, 180)',
        ),
        yaxis2=pygo.YAxis(
            side='right',
            overlaying='y',
            range=[0, max(df['volume']) * m_y2k],
        ),
    )  # fig.update
    r_vol = pygo.Bar(
        x=df.index,  #df['xtim'],
        y=df['volume'],
        name='volume',
        yaxis='y2',
        opacity=0.6,
        marker=dict(
            color='rgb(158,202,225)',
            line=dict(
                color='rgb(8,48,107)',
                width=1.5,
            ),
        ),
    )  #r_vol
    #
    fig['data'].extend([r_vol])
    #
    pyplt(fig, filename=ftg, show_link=False)
Example #2
0
def get_layout(title, labels, labels2=None, plot_log=False):
    if plot_log:
        yaxis = go.YAxis(title='Stężenie molowe [μM]',
                         type='log',
                         tickvals=logscale())
        t = 'Estymowane wartości stężeń w próbce CSF - {}'.format(title)

        return go.Layout(
            xaxis=go.XAxis(
                title='Analizowana próbka [#]',
                ticks="",
                showticklabels=True,
                ticktext=labels,
                tickvals=[i for i in range(len(labels))],
                zeroline=False,
            ),
            yaxis=yaxis,
            title=t,
        )

    else:
        xaxis = go.XAxis(
            title='Błąd względny [%]',
            zeroline=False,
        )
        t = 'Maksymalny błąd względny estymacji stężenia - {}'.format(title)

        return go.Layout(
            xaxis=xaxis,
            yaxis=go.YAxis(
                title='Analizowana próbka [#]',
                ticks="",
                showticklabels=True,
                ticktext=labels,
                tickvals=[i for i in range(len(labels))],
                zeroline=False,
                titlefont=dict(color='#1f77b4'),
                tickfont=dict(color='#1f77b4'),
            ),
            yaxis2=dict(
                title='Analizowana próbka [#]',
                ticks="",
                showticklabels=True,
                ticktext=labels2,
                tickvals=[i for i in range(len(labels2))],
                zeroline=False,
                overlaying='y',
                side='right',
                titlefont=dict(color='#ff7f0e'),
                tickfont=dict(color='#ff7f0e'),
            ),
            title=t,
        )
Example #3
0
def pop_count_graph(obs_inds, inds, sur_inds_sur, inds_sur):
    #graph that counts households + individuals
    xaxis = ['Groups', 'Individuals']

    trace1 = go.Bar(x=xaxis,
                    y=[obs_inds.count(), inds.count()],
                    name='Observed',
                    marker=dict(color=["#6CD6C3", "#6CD6C3"]))
    trace2 = go.Bar(x=xaxis,
                    y=[sur_inds_sur.count(),
                       inds_sur.count()],
                    name='Surveyed',
                    marker=dict(color=["#DDCAF5", "#DDCAF5"]))

    data = [trace1, trace2]

    layout = go.Layout(title='Observed Households and Individuals',
                       title_x=0.5,
                       font=dict(size=12, family='sans-serif'),
                       barmode='stack',
                       xaxis=dict(tickvals=['Groups', 'Individuals']),
                       paper_bgcolor='rgba(0,0,0,0)',
                       plot_bgcolor='rgba(0,0,0,0)',
                       yaxis=go.YAxis(showticklabels=False))

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

    return figure
Example #4
0
def line_per_odper_fitting_fuction(dataframe, function, filename):
    """line graph for long tail analysis. X: percentage Y: od percentage"""

    # calculate new x's and y's
    x_new = np.linspace(0.5, 1, 50)
    y_new = function(x_new)

    data_origin = go.Scatter(
        x=dataframe['percentage'],  # assign x as the dataframe column 'x'
        y=dataframe['od_needed'],
        mode='markers',
        marker=go.Marker(color='rgb(255, 127, 14)'),
        name='Data')

    data_fitting = go.Scatter(x=x_new,
                              y=y_new,
                              mode='lines',
                              marker=go.Marker(color='rgb(31, 119, 180)'),
                              name='Fit')

    data = [data_origin, data_fitting]

    layout = go.Layout(
        title='Coverage and OD Relationship with Polynomial Fit in Python',
        plot_bgcolor='rgb(229, 229, 229)',
        xaxis=go.XAxis(zerolinecolor='rgb(255,255,255)',
                       gridcolor='rgb(255,255,255)'),
        yaxis=go.YAxis(zerolinecolor='rgb(255,255,255)',
                       gridcolor='rgb(255,255,255)'))

    fig = go.Figure(data=data, layout=layout)
    py.plot(fig, filename=filename)
def get_hits_per_hour(end):
    data = get_line_results(end)

    # Find the last date which contains data
    max_time = max([d.newTime for d in data])
    max_date = datetime.datetime.strptime(max_time, '%Y-%m-%d %H:%M:%S')
    max_date += datetime.timedelta(minutes=30)

    graph = [
        go.Bar(x=[d.newTime for d in data],
               y=[d.count for d in data],
               marker=dict(color=get_color(end)))
    ]

    layout = go.Layout(
        autosize=True,
        height=600,
        title='Number of hits per hour',
        plot_bgcolor='rgba(249,249,249,1)',
        showlegend=False,
        xaxis=go.XAxis(title='Date',
                       range=[max_date - datetime.timedelta(days=2),
                              max_date]),
        yaxis=go.YAxis(title='Hits'))
    return plotly.offline.plot(go.Figure(data=graph, layout=layout),
                               output_type='div',
                               show_link=False)
Example #6
0
def get_horizontal_bar_layout(
    annotations, shapes,
    title='',
    x_axis_title='',
    width='370',
    height='530',
    left=45, r=20, t=30, b=30,
):
    return go.Layout(
        title=title,
        width=width,
        height=height,
        margin={
            'pad': .5,
            'l': left, 'r': r, 't': t, 'b': b,
        },
        xaxis=go.XAxis(
            title=x_axis_title,
            zeroline=False,
            showticklabels=False,
            fixedrange=True,
        ),
        yaxis=go.YAxis(
            fixedrange=True,
        ),
        annotations=annotations,
        shapes=shapes,
    )
Example #7
0
    def plot(self, showticklabels=False):
        title = self.titlestring % (self.DS.name)
        xaxis = go.XAxis(
            title="Observations",
            ticktext=self.DS.D.index,
            ticks="",
            showticklabels=False,
            tickvals=[i for i in range(len(self.DS.D.index))])
        yaxis = go.YAxis(
            title="Dimensions",
            ticktext=self.DS.D.columns,
            ticks="",
            showticklabels=showticklabels,
            tickvals=[i for i in range(len(self.DS.D.columns))])
        layout = self._get_layout(title, xaxis, yaxis)

        maximum = self.DS.D.max().max()
        trace = go.Heatmap(
            z=self.DS.D.as_matrix().T,
            zmin=-maximum,
            zmax=maximum,
            colorscale=self.BuRd)
        data = [trace]
        fig = dict(data=data, layout=layout)
        return self.makeplot(fig, "agg/" + self.shortname)
Example #8
0
def plotScatter3D(df, mytitle, allDict, notebook=True):
    import plotly
    import plotly.graph_objs as go
    statTooltips = []
    doctopics = []
    docdates = []
    for key in df.index:
        try:
            statTooltips.append(tooltipText(allDict[key]))
        except:
            print(key, "not found")

    colorDropdown = widgets.Dropdown(description='Topics:',
                                     value=df["specGroup"][0],
                                     options=df["specGroup"])
    trace = go.Scatter3d(
        x=df['pca-one'],
        y=df['pca-two'],
        z=df['pca-three'],
        mode='markers',
        marker=dict(
            size=df["size"],
            color=df["specGroup"],
            colorscale='Viridis',
            colorbar=dict(title="Topic<br>Relevance"),
            # symbol=df["specGroup"], # TODO actually want Feedname
            showscale=True,
            opacity=0.6),
        # symbol=df["specGroup"],
        text=statTooltips,
        textfont=dict(family="sans serif", size=8, color='crimson'),
        hoverinfo='text')

    # Configure the layout.
    #    layout = go.Layout(margin={'l': 0, 'r': 0, 'b': 0, 't': 0})
    layout = go.Layout(showlegend=False,
                       title=mytitle,
                       margin={
                           'l': 0,
                           'r': 0,
                           'b': 50,
                           't': 30
                       },
                       scene=go.Scene(
                           xaxis=go.XAxis(title='PCA Dimension<br>Reduced X'),
                           yaxis=go.YAxis(title='PCA Dimension<br>Reduced Y'),
                           zaxis=go.ZAxis(title='PCA Dimension<br>Reduced Z')))

    data = [trace]
    plot_figure = go.Figure(data=data, layout=layout)
    camera = dict(eye=dict(x=1.5, y=1.5, z=0.1))
    plot_figure.update_layout(scene_camera=camera)
    #    plt.tight_layout()

    # Render the plot.
    pl = plotly.offline.iplot(plot_figure)
    pl
    if not notebook:
        plotly.offline.plot(plot_figure, filename='file.html')
    return trace
Example #9
0
def prepare_graph(filename):
    """Prepare a graph to plot.

    Args:
        filename: Name of the .gml file.

    Returns:
        fig : The figure prepare for plotly.iplot function.
    """

    G = InteractiveGraph(filename)
    axis = dict(
        showline=False,
        zeroline=False,
        showgrid=False,
        showticklabels=False,
    )
    layout = dict(annotations=G.make_annotations(),
                  font=dict(size=15),
                  showlegend=False,
                  xaxis=go.XAxis(axis),
                  yaxis=go.YAxis(axis),
                  margin=dict(l=10, r=10, b=15, t=15),
                  hovermode='closest',
                  plot_bgcolor='rgb(248,248,248)')
    data = go.Data([G.lines, G.dots])
    fig = dict(data=data, layout=layout)
    fig['layout'].update(annotations=G.make_annotations(G.ids, 15))
    return fig
Example #10
0
def plot_stress_meshed(mesh,stress):
    """
    Plots the stress on a real mesh using plotly
    :param mesh: The mesh
    :param stress: The stress
    """
    data = [
        go.Mesh3d(
            x=[0, 1, 2, 0],
            y=[0, 0, 1, 2],
            z=[0, 2, 0, 1],
            colorbar=go.ColorBar(
                title='z'
            ),
            colorscale=[[0, 'rgb(255, 0, 0)'],
                        [0.5, 'rgb(0, 255, 0)'],
                        [1, 'rgb(0, 0, 255)']],
            intensity=[0, 0.33, 0.66, 1],
            i=[0, 0, 0, 1],
            j=[1, 2, 3, 2],
            k=[2, 3, 1, 3],
            name='y',
            showscale=True
        )
    ]
    layout = go.Layout(
        xaxis=go.XAxis(
            title='x'
        ),
        yaxis=go.YAxis(
            title='y'
        )
    )
    fig = go.Figure(data=data, layout=layout)
    py.plot(fig, filename='/home/leon/Documents/RCI/TMA4220_NumPDE/3d-mesh-tetrahedron-python')
Example #11
0
def make_layout(
        metadata,
        title,
        fixed=False,
        x_axis=None,
        y_axis=None,
        **kwargs
):
    if not y_axis:
        y_axis = dict()
    y_axis.setdefault('title', 'Frequency')
    y_axis.setdefault('autorange', True)
    y_axis = go.YAxis(**y_axis)

    if not x_axis:
        x_axis = dict()
    x_axis.setdefault('title', 'Deviation (%)')
    x_axis = go.XAxis(**x_axis)

    if fixed:
        x_axis['range'] = [
            100.0 * metadata['x_min'],
            100.0 * min(4.0, metadata['x_max'])]
        x_axis['autorange'] = False

    return go.Layout(title=title, xaxis=x_axis, yaxis=y_axis, **kwargs)
Example #12
0
 def pcaWiki(self,file):
     self.formDataPCA(file)           
     X_std = StandardScaler().fit_transform(self.X)
     sklearn_pca = sklearnPCA(n_components=2)
     Y_sklearn = sklearn_pca.fit_transform(X_std)
     traces = []
 
     for name in self.names:
         trace = go.Scatter(
             x=Y_sklearn[self.y==name,0],
             y=Y_sklearn[self.y==name,1],
             mode='markers',
             name=name,
             marker=go.Marker(
                 size=12,
                 line=go.Line(
                     color='rgba(217, 217, 217, 0.14)',
                     width=0.5),
                 opacity=0.8))
         traces.append(trace)
     data = go.Data(traces)
     layout = go.Layout(xaxis=go.XAxis(title='PC1', showline=False),
                     yaxis=go.YAxis(title='PC2', showline=False))
     fig = go.Figure(data=data, layout=layout)
     if (self.outputType == 'file'):
         print(py.plot(fig,filename='pca')) 
     else:
         return (py.plot(fig,include_plotlyjs='False',output_type='div')) 
Example #13
0
def drDF_tick(df, ftg='tmp/tmp_plotly.html', m_title='tick数据'):
    r_price = pygo.Scatter(x=df['xtim'], y=df['price'], name='price')
    r_vol = pygo.Bar(
        x=df['xtim'],
        y=df['volume'],
        name='volume',
        #yaxis= 'y2'
    )

    lay = pygo.Layout(
        title=m_title,
        xaxis=pygo.XAxis(
            #autorange=True,
            gridcolor='rgb(180, 180, 180)',
            #gridwidth=1,
            dtick=5,
            mirror='all',
            showgrid=True,
            showline=True,
            ticks='outside',  #'inside',
            tickangle=-20,
            #
            type='category',
            categoryarray=df.index,
        ),
        yaxis2=pygo.YAxis(
            side='right',
            overlaying='y',
            range=[0, max(df['volume']) * 3],
        ),
    )  #lay = pygo.Layout(

    xdat = pygo.Data([r_price, r_vol])
    fig = pygo.Figure(data=xdat, layout=lay)
    pyplt(fig, filename=ftg, show_link=False)
Example #14
0
    def plot(self, showticklabels=False):
        title = self.titlestring % (self.DS.name, self.DS.clustname,
                                    self.DS.levels)
        self.shortname = self.DS.shortclustname + self.shortname

        #When number of samples is too high, need to downsample
        freq = [c.shape[0] for c in self.DS.clusters[self.DS.levels]]
        if sum(freq) > 500:
            freq = [round((x / sum(freq)) * 500) for x in freq]

        means = []
        for i, c in enumerate(self.DS.clusters[self.DS.levels]):
            means += [np.average(c, axis=0)] * freq[i]
        X = np.column_stack(means)
        print(X.shape)
        trace = go.Heatmap(y=self.DS.columns[::-1],
                           z=np.flipud(X),
                           zmin=-np.max(X),
                           zmax=np.max(X),
                           colorscale=self.BuRd)
        data = [trace]
        xaxis = go.XAxis(title="Clusters",
                         showticklabels=False,
                         ticks="",
                         mirror=True,
                         tickvals=[i for i in range(X.shape[1])])
        yaxis = go.YAxis(title="Dimensions",
                         showticklabels=showticklabels,
                         ticks="",
                         mirror=True)
        layout = dict(title=title, xaxis=xaxis, yaxis=yaxis)
        fig = dict(data=data, layout=layout)
        return self.makeplot(fig, "agg/" + self.shortname)
Example #15
0
    def plot(self, showticklabels=False):
        title = self.titlestring % (self.DS.name, self.DS.clustname,
                                    self.DS.levels)
        self.shortname = self.DS.shortclustname + self.shortname
        data = []
        colors = get_spaced_colors(len(self.DS.clusters[self.DS.levels]))

        #When number of samples is too high, need to downsample
        freq = [c.shape[0] for c in self.DS.clusters[self.DS.levels]]
        if sum(freq) > 300:
            freq = [round((x / sum(freq)) * 300) for x in freq]

        for i, c in enumerate(self.DS.clusters[self.DS.levels]):
            data.append(
                go.Scatter(x=np.average(c, axis=0),
                           y=self.DS.columns,
                           mode="lines",
                           line=dict(width=np.sqrt(freq[i]), color=colors[i]),
                           name="cluster " + str(i)))
        xaxis = go.XAxis(title="Mean Values",
                         showticklabels=False,
                         mirror=True)
        yaxis = go.YAxis(title="Dimensions",
                         showticklabels=showticklabels,
                         mirror=True)
        layout = dict(title=title, xaxis=xaxis, yaxis=yaxis)
        fig = dict(data=data, layout=layout)
        return self.makeplot(fig, "agg/" + self.shortname)
Example #16
0
    def plot(self):
        """Constructs a distance matrix heatmap using the :obj:`DistanceMatrix` object, in plotly.

        """
        title = self.titlestring % (self.DS.name)
        xaxis = go.XAxis(title=self.DS.D.index.name,
                         ticktext=self.DS.D.index,
                         ticks="",
                         showticklabels=False,
                         showgrid=False,
                         mirror=True,
                         tickvals=[i for i in range(len(self.DS.D.index))])
        yaxis = go.YAxis(scaleanchor="x",
                         title=self.DS.D.index.name,
                         ticktext=self.DS.D.index,
                         showgrid=False,
                         ticks="",
                         showticklabels=False,
                         mirror=True,
                         tickvals=[i for i in range(len(self.DS.D.index))])
        layout = dict(title=title, xaxis=xaxis, yaxis=yaxis)
        trace = go.Heatmap(z=self.DS.D.as_matrix().T)
        data = [trace]
        fig = dict(data=data, layout=layout)
        return self.makeplot(fig, "agg/" + self.shortname)
Example #17
0
def generate_plot_30d(queue_name):
    df = Datasources.get_latest_data_for(
        "aws-athena-query-results-lancs-history-30d")
    filtered_df = df[df["match_apf_queue"] == queue_name]

    if len(filtered_df) == 0:
        return None

    filtered_df.insert(4, "long_jobs",
                       filtered_df["total_jobs"] - filtered_df["short_jobs"])

    trace1 = go.Bar(
        x=filtered_df["job_date"],
        y=filtered_df["short_jobs"],
        name="Short jobs",
        marker=dict(color="#C21E29", ),
        offset=0.5,
    )

    trace2 = go.Bar(
        x=filtered_df["job_date"],
        y=filtered_df["long_jobs"],
        name="Long jobs",
        marker=dict(color="#3A6CAC", ),
        offset=0.5,
    )

    data = [trace1, trace2]

    min_date = df["job_date"].min()
    max_date = df["job_date"].max()

    layout = go.Layout(
        title="30 days",
        barmode="stack",
        xaxis=go.XAxis(
            title="Date",
            autorange=False,
            range=[min_date, max_date],
            fixedrange=True,
            showgrid=True,
            gridcolor="darkgrey",
        ),
        yaxis=go.YAxis(
            title="Jobs",
            fixedrange=True,
            showgrid=True,
            gridcolor="darkgrey",
        ),
        margin=go.Margin(l=55, r=45, b=50, t=30, pad=4),
    )

    fig = {
        "data": data,
        "layout": layout,
    }

    return dcc.Graph(id="queue-30d",
                     figure=fig,
                     config={'displayModeBar': False})
    def plot3Dgraph(self, fig, x, y, z):
        import plotly.graph_objs as go

        surface = go.Surface(x=x, y=y, z=z)
        data = go.Data([surface])

        layout = go.Layout(
            title='Parametric Plot',
            scene=go.Scene(xaxis=go.XAxis(gridcolor='rgb(255, 255, 255)',
                                          zerolinecolor='rgb(255, 255, 255)',
                                          showbackground=True,
                                          backgroundcolor='rgb(230, 230,230)'),
                           yaxis=go.YAxis(gridcolor='rgb(255, 255, 255)',
                                          zerolinecolor='rgb(255, 255, 255)',
                                          showbackground=True,
                                          backgroundcolor='rgb(230, 230,230)'),
                           zaxis=go.ZAxis(
                               gridcolor='rgb(255, 255, 255)',
                               zerolinecolor='rgb(255, 255, 255)',
                               showbackground=True,
                               backgroundcolor='rgb(230, 230,230)')))

        fig = go.Figure(data=data,
                        layout=go.Layout(title='Offline Plotly Testing',
                                         width=800,
                                         height=500,
                                         xaxis=dict(title='X-axis'),
                                         yaxis=dict(title='Y-axis')))

        plot(fig, show_link=False)
Example #19
0
def layout(ts, *args, **kwargs):
    """ Make a plotly layout from timespectra attributes """

    kwargs.setdefault('title', _parsenull(ts.name))
    kwargs.setdefault('plot_bgcolor', '#EFECEA')  #gray
    kwargs.setdefault('showlegend', False)

    # Map x,y title into grobs.XAxis and grobs.YAxis
    xtitle = _parsenull(kwargs.pop('xtitle', ts.specunit))
    ytitle = _parsenull(kwargs.pop('ytitle', ts.iunit))

    kwargs['xaxis'] = grobs.XAxis(title=xtitle)
    kwargs['yaxis'] = grobs.YAxis(title=ytitle)

    layout = grobs.Layout(**kwargs)

    axis_style = dict(
        zeroline=False,  # remove thick zero line
        gridcolor='#FFFFFF',  # white grid lines
        ticks='outside',  # draw ticks outside axes 
        ticklen=8,  # tick length
        tickwidth=1.5)  #   and width

    # Can I just set these in XAxis and YAxis __init__?
    layout['xaxis'].update(axis_style)
    layout['yaxis'].update(axis_style)
    return layout
Example #20
0
 def pca(self,winSize):
     data = np.zeros((len(self.data),len(self.data['FUNC'][winSize])))
     i=0
     for dEl in sorted(self.data):
         self.data[dEl][winSize] = normalizeMaxMin(self.data[dEl][winSize])
         data[i] = self.data[dEl][winSize]
         i+=1
         
     X_std = StandardScaler().fit_transform(np.transpose(data))
     sklearn_pca = sklearnPCA(n_components=2)
     Y_sklearn = sklearn_pca.fit_transform(X_std)
     traces = []
     
     trace = go.Scatter(
         x=Y_sklearn[:,0],
         y=Y_sklearn[:,1],
         mode='markers',
         marker = go.Marker(
             size=12,
             line= go.Line(
                 color='rgba(217, 217, 217, 0.14)',
                 width=0.5),
             opacity=0.8))
     traces.append(trace)
     
     
     data = go.Data(traces)
     layout = go.Layout(xaxis = go.XAxis(title='PC1', showline=False),
                        yaxis = go.YAxis(title='PC2', showline=False))
     fig = go.Figure(data=data, layout=layout)
     if self.outputType=='file':
         print(py.plot(fig, filename='pca.html'))
     else:
         return py.plot(fig, output_type='div')
Example #21
0
    def _plot_score_pca_matrix(self, plot_pca_matrix, n_components):

        output_directory = os.path.join(self.scratch, str(uuid.uuid4()))
        self._mkdir_p(output_directory)
        result_file_paths = []

        all_pairs = list(itertools.combinations(range(1, n_components + 1), 2))

        for pair in all_pairs:
            first_component = pair[0]
            second_component = pair[1]
            result_file_path = os.path.join(
                output_directory,
                'pca_score_plot_{}_{}.html'.format(first_component,
                                                   second_component))

            traces = self._build_2_comp_trace(
                plot_pca_matrix,
                'principal_component_{}'.format(first_component),
                'principal_component_{}'.format(second_component))

            data = go.Data(traces)
            layout = go.Layout(
                xaxis=go.XAxis(title='PC{}'.format(first_component),
                               showline=False),
                yaxis=go.YAxis(title='PC{}'.format(second_component),
                               showline=False))
            fig = go.Figure(data=data, layout=layout)

            plot(fig, filename=result_file_path)

            result_file_paths.append(result_file_path)

        return result_file_paths
Example #22
0
 def plot(self):
     title = self.titlestring % (self.DS.name)
     D = self.DS.D.as_matrix().T
     d, n = D.shape
     U, _, _ = np.linalg.svd(D, full_matrices=False)
     xaxis = go.XAxis(
         title="Eigenvectors",
         ticktext=["Eigenvector %s" % i for i in range(1, d + 1)],
         ticks="",
         showgrid=False,
         showticklabels=False,
         mirror=True,
         tickvals=[i for i in range(d)])
     yaxis = go.YAxis(
         title="Eigenvector Components",
         scaleanchor="x",
         showgrid=False,
         ticktext=["Component %s" % i for i in range(1, d + 1)],
         ticks="",
         showticklabels=False,
         mirror=True,
         tickvals=[i for i in range(d)])
     layout = dict(title=title, xaxis=xaxis, yaxis=yaxis)
     trace = go.Heatmap(z=U)
     data = [trace]
     fig = dict(data=data, layout=layout)
     return self.makeplot(fig, "agg/" + self.shortname)
Example #23
0
def PlotSingleFundamental(data, fundamental='pe', area=None, industry=None):
    if area != None:
        data = data.loc[data['area'] == area]
    else:
        area = '全地区'

    if industry != None:
        data = data.loc[data['industry'] == industry]
        data = data.sort_values(fundamental)
        Fundamental = go.Bar(x=data['name'],
                             y=np.log(data[fundamental].abs() + 1) *
                             np.sign(data[fundamental]),
                             name=fundamental,
                             text=data[fundamental],
                             textposition='auto',
                             opacity=0.6)
    else:
        data = data.groupby(by=['industry'],
                            as_index=False)[fundamental].mean()
        data = data.sort_values(fundamental)
        Fundamental = go.Bar(x=data['industry'],
                             y=np.log(data[fundamental].abs() + 1) *
                             np.sign(data[fundamental]),
                             name=fundamental,
                             text=data[fundamental],
                             textposition='auto',
                             opacity=0.6)
        industry = '分行业'
    chartdata = [Fundamental]

    num = len(data.index)
    if num > 15:
        w = 1600
        h = 1024
    else:
        w = 800
        h = 600

    RANGE = list(
        range(
            int(
                math.floor(np.log(abs(data[fundamental].min()) + 1)) *
                np.sign(data[fundamental].min())),
            int(
                math.ceil(
                    np.log(abs(data[fundamental].max() + 1)) *
                    np.sign(data[fundamental].max())))))
    VAL = np.round((np.exp(np.abs(RANGE)) - 1) * np.sign(RANGE)).tolist()

    layout = go.Layout(title=area + industry + fundamental + '比较',
                       yaxis=go.YAxis(
                           title=fundamental,
                           tickvals=RANGE,
                           ticktext=VAL,
                       ))
    fig = go.Figure(data=chartdata, layout=layout)
    py.image.save_as(fig,
                     filename='Chart/' + area + industry + fundamental +
                     '比较.png')
def dist_plot(df,
              groupby=None,
              val=None,
              bin_size=1,
              title=None,
              show_hist=True,
              show_kde=True,
              show_rug=True,
              show_legend=True,
              figsize=None,
              outfile=None,
              xlabel=None,
              ylabel=None):

    if groupby is None:
        fig = FF.create_distplot([df[c] for c in df.columns],
                                 df.columns.values.tolist(),
                                 bin_size=bin_size,
                                 show_rug=show_rug,
                                 show_curve=show_kde)
    else:
        groups = sorted(df[groupby].unique().tolist(), reverse=True)
        data = []
        if val is None:
            val = df.columns.drop(groupby)[
                0]  # choose first non-groupby column

        for group in groups:
            mask = df[groupby] == group
            data.append(df.loc[mask, val])

        fig = FF.create_distplot(data,
                                 groups,
                                 bin_size=bin_size,
                                 show_hist=show_hist,
                                 show_rug=show_rug,
                                 show_curve=show_kde)

    fig['layout'].update(showlegend=show_legend)

    if title:
        fig['layout'].update(title=title)

    if xlabel:
        fig['layout'].update(xaxis=go.XAxis(title=xlabel))

    if ylabel:
        fig['layout'].update(yaxis=go.YAxis(title=ylabel))

    if figsize and len(figsize) == 2:
        fig['layout'].update(width=figsize[0])
        fig['layout'].update(height=figsize[1])

    ol.iplot(fig, show_link=False)

    # write figure to HTML file
    if outfile:
        print('Exporting copy of figure to %s...' % outfile)
        ol.plot(fig, auto_open=False, filename=outfile)
def plot_diff(ref_df, dist_df, t='', xlabel='', ylabel='', col='msm'):
    import plotly.graph_objs as go
    from plotly.offline import iplot

    plot_df = dist_df.join(ref_df, rsuffix='_ref', how='inner').dropna()

    text_tmpl = ('{}{}<br>X: moc={:.3f} spat={:.3f} spec={:.3f}'
                 '<br>Y: moc={:.3f} spat={:.3f} spec={:.3f}')

    traces = []
    adducts = plot_df.index.get_level_values('adduct').unique()
    for adduct in adducts:
        df = plot_df.xs(adduct, level='adduct')
        txt = df.reset_index().apply(
            lambda r: text_tmpl.format(r.sf, adduct, r.moc_ref, r.spat_ref, r.
                                       spec_ref, r.moc, r.spat, r.spec),
            axis=1,
        )

        if df.empty:
            continue

        traces.append(
            go.Scatter(
                x=df['{}_ref'.format(col)],
                y=df['{}'.format(col)],
                text=txt,
                mode='markers',
                name=adduct,
            ))

    data = go.Data(traces)
    fig = go.Figure(
        data=data,
        layout=go.Layout(
            autosize=False,
            height=500,
            hovermode='closest',
            title=t + ' \'{}\' values'.format(col),
            width=500,
            xaxis=go.XAxis(
                autorange=False,
                range=[-0.05675070028979684,
                       1.0323925590539844],  # what the f**k is this?
                title=xlabel,
                type='linear',
            ),
            yaxis=go.YAxis(
                autorange=False,
                range=[-0.0015978995361995152,
                       1.0312345837176764],  # what the f**k is this?
                title=ylabel,
                type='linear',
            ),
        ),
    )
    iplot(fig, filename='ref_dist_msm_scatter')
    tmp_df = plot_df.dropna()
    return tmp_df
Example #26
0
def cluster_test():

    dataSet = getDataSetFromDatabase()

    labels = cluster(dataSet)

    # transpose to work with Plotly-format (don't remember if it is sklear.cluster or plotly that is counterintuitive)
    dataToChart = dataSet.transpose()

    # create multi dimensional array of data by label
    segmentedData = [[[] for _ in xrange(3)] for _ in xrange(numClusters)]

    for num, label in enumerate(labels):
        print (str(num) + ' ' + str(label))
        segmentedData[label][0].append(dataToChart[0][num])
        segmentedData[label][1].append(dataToChart[1][num])
        segmentedData[label][2].append(dataToChart[2][num])

    if debug:
        print(segmentedData)

    # create traces for plotly
    traces = []
    baseColor = 100
    i = 0
    while i < numClusters:
        trace = go.Scatter3d(
            x=segmentedData[i][0],
            y=segmentedData[i][1],
            z=segmentedData[i][2],
            mode='markers',
            marker=dict(
                size=12,
                line=dict(
                    color='rgba(baseColor+(i*2), baseColor+(i*2), baseColor+(i*2), 0.14)',
                    width=0.5
                ),
                opacity=0.8
            ),
            # @todo: fix names list for plotly
            #text=names
        )
        traces.append(trace)
        i+=1

    layout = go.Layout(
        scene=go.Scene(
            xaxis=go.XAxis(title='Carbs', tickprefix='Carbs ', showtickprefix='first'),
            yaxis=go.YAxis(title='Fat', tickprefix='Fat ', showtickprefix='first'),
            zaxis=go.ZAxis(title='Protein', tickprefix='Protein ', showtickprefix='first')
        ),
        height = 800,
        width = 800,
    )

    fig = go.Figure(data=traces, layout=layout)
    graphJSON = json.dumps(fig, cls=plotly.utils.PlotlyJSONEncoder)
    return render_template('cluster-test.html', graphJSON=graphJSON)
Example #27
0
def drDF_mul_xline(df,
                   ftg='tmp/tmp_plotly.html',
                   m_tkAng=-20,
                   m_dtick=5,
                   m_title='多周期分时数据',
                   xlst=['t1', 't5', 't15', 't30', 't60']):
    r_vol = pygo.Bar(
        x=df.index,  #df['xtim'],
        y=df['volume'],
        name='volume',
        yaxis='y2',
        opacity=0.6,
        marker=dict(
            color='rgb(158,202,225)',
            line=dict(
                color='rgb(8,48,107)',
                width=1.5,
            ),
        ),
    )  #r_vol
    #
    xdat = pygo.Data([r_vol])
    for xsgn in xlst:
        r_xnam = 'r_' + xsgn
        r_xnam = pygo.Scatter(
            x=df.index,
            y=df[xsgn],
            name=xsgn,
            connectgaps=True,
        )
        #
        xdat.extend([r_xnam])
    #
    lay = pygo.Layout(
        title=m_title,
        xaxis=pygo.XAxis(
            gridcolor='rgb(180, 180, 180)',
            mirror='all',
            showgrid=True,
            showline=True,
            ticks='outside',  #'inside',
            #
            dtick=m_dtick,
            tickangle=m_tkAng,
            #
            type='category',
            categoryarray=df.index,
        ),
        yaxis2=pygo.YAxis(
            side='right',
            overlaying='y',
            range=[0, max(df['volume']) * 3],
        ),
    )  #lay = pygo.Layout(

    #xdat = pygo.Data([r_t1,r_t5,r_t15,r_t30,r_t60])
    fig = pygo.Figure(data=xdat, layout=lay)
    pyplt(fig, filename=ftg, show_link=False)
Example #28
0
    def plotHidroParcial(self, dfPicos, limiar, nomeGrafico):
        #limiar = self.dados[self.nPosto].quantile(limiar)
        median = self.dados[self.nPosto].median()
        #mean = self.dados[self.nPosto].mean()

        if self.nPosto == None:
            return 'Erro! forneça o n° do Posto'
        else:
            traceHidro = go.Scatter(x=self.dados.index,
                                    y=self.dados[self.nPosto],
                                    name=self.nPosto,
                                    line=dict(color='#17BECF', width=1),
                                    opacity=1)
            traceLimiar = go.Scatter(x=self.dados.index,
                                     y=[limiar] * len(self.dados),
                                     name="Limiar",
                                     line=dict(color='#858585', width=1),
                                     opacity=1)
            """traceMedian = go.Scatter(x=self.dados.index,
                y=[median]*len(self.dados),
                name = "Mediana",
                line = dict(color = 'red',
                             width = 1),
                opacity = 1)"""
            pointInicio = go.Scatter(
                x=dfPicos.Inicio,
                y=self.dados[self.nPosto].loc[dfPicos.Inicio],
                name="Inicio do Evento",
                mode='markers',
                marker=dict(color='blue', size=5),
                opacity=1)
            pointFim = go.Scatter(x=dfPicos.Fim,
                                  y=self.dados[self.nPosto].loc[dfPicos.Fim],
                                  name="Fim do Evento",
                                  mode='markers',
                                  marker=dict(color='red', size=5),
                                  opacity=1)
            pointVazao = go.Scatter(
                x=dfPicos.index,
                y=self.dados[self.nPosto].loc[dfPicos.index],
                name="Pico",
                mode='markers',
                marker=dict(color='green', size=5),
                opacity=1)

            data = [traceHidro, traceLimiar, pointInicio, pointFim, pointVazao]
            bandxaxis = go.XAxis(title="Anos", )

            bandyaxis = go.YAxis(title="Vazão(m³/s)", )
            layout = dict(title="Hidrograma Série Duração Parcial (%s)" %
                          nomeGrafico.title(),
                          xaxis=bandxaxis,
                          yaxis=bandyaxis,
                          font=dict(family='Courier New, monospace',
                                    size=18,
                                    color='#7f7f7f'))
            fig = dict(data=data, layout=layout)
        py.offline.plot(fig, filename='gráficos/%s' % nomeGrafico + '.html')
Example #29
0
def plot_siso_response(time,
                       input,
                       output,
                       title='Time Response',
                       x_lab='Time [s]',
                       x_lim=None,
                       input_y_lab='Input',
                       input_y_lim=None,
                       output_y_lab='Output',
                       output_y_lim=None,
                       subplots=True):
    """Plots a time history of the input and output of a SISO system."""

    xaxis = gr.XAxis(title=x_lab, range=x_lim)

    if subplots:
        yaxis = gr.YAxis(title=input_y_lab,
                         range=input_y_lim,
                         domain=[0.0, 0.49])
        yaxis2 = gr.YAxis(title=output_y_lab,
                          range=output_y_lim,
                          domain=[0.51, 1.0])
        layout = gr.Layout(title=title,
                           xaxis=xaxis,
                           yaxis=yaxis,
                           yaxis2=yaxis2,
                           showlegend=False)

        output_trace = gr.Scatter(name=output_y_lab,
                                  x=time,
                                  y=output,
                                  yaxis='y2')
    else:
        yaxis = gr.YAxis(range=output_y_lim)
        layout = gr.Layout(title=title, xaxis=xaxis, yaxis=yaxis)

        output_trace = gr.Scatter(name=output_y_lab, x=time, y=output)

    input_trace = gr.Scatter(name=input_y_lab, x=time, y=input)

    data = gr.Data([input_trace, output_trace])

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

    return fig
Example #30
0
    def _plot_loading_pca_matrix(self, components_df, n_components):

        output_directory = os.path.join(self.scratch, str(uuid.uuid4()))
        self._mkdir_p(output_directory)
        result_file_paths = []

        all_pairs = list(itertools.combinations(range(1, n_components + 1), 2))

        for pair in all_pairs:
            first_component = pair[0]
            second_component = pair[1]
            result_file_path = os.path.join(
                output_directory,
                'pca_loading_plot_{}_{}.html'.format(first_component,
                                                     second_component))

            traces = list()
            data = go.Data(traces)
            layout = go.Layout(
                xaxis=go.XAxis(title='PC{}'.format(first_component),
                               showline=False),
                yaxis=go.YAxis(title='PC{}'.format(second_component),
                               showline=False))
            fig = go.Figure(data=data, layout=layout)

            coeff = list()
            coeff.append(components_df['principal_component_{}'.format(
                first_component)])
            coeff.append(components_df['principal_component_{}'.format(
                second_component)])
            coeff = np.transpose(coeff)

            loading_x = list()
            loading_y = list()
            loading_text = list()
            for idx, position in enumerate(coeff):
                loading_x.append(0)
                loading_y.append(0)
                loading_text.append('0')

                loading_x.append(position[0])
                loading_y.append(position[1])
                loading_text.append(components_df.index[idx])

            fig.add_trace(
                go.Scatter(x=loading_x,
                           y=loading_y,
                           mode="lines+markers",
                           name="loading plot",
                           text=loading_text,
                           textposition="bottom center"))

            plot(fig, filename=result_file_path)

            result_file_paths.append(result_file_path)

        return result_file_paths