コード例 #1
0
ファイル: result_parser.py プロジェクト: ishmur/nmr-msc
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,
        )
コード例 #2
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})
コード例 #3
0
def graph_loss(mean_loss, loss, num_epochs, title):
    flat_list1 = [item for sublist in loss for item in sublist]
    flat_list2 = [item for sublist in mean_loss for item in sublist]

    num_steps = len(loss[0])

    bandxaxis = go.XAxis(title='Epochs',
                         range=[0, len(flat_list1)],
                         showgrid=False,
                         showline=False,
                         ticks='outside',
                         showticklabels=True,
                         mirror=True,
                         linewidth=2,
                         ticktext=[str(i + 1) for i in range(num_epochs)],
                         tickvals=[(i + 1) * num_steps
                                   for i in range(num_epochs)])

    plotly.offline.plot({
        "data": [
            go.Scatter(y=flat_list1, name='batch loss', line=dict(width=0.2)),
            go.Scatter(y=flat_list2,
                       name='mean batch loss per epoch',
                       line=dict(width=5))
        ],
        "layout":
        go.Layout(xaxis=bandxaxis, yaxis=dict(title=''), title=title)
    })
コード例 #4
0
ファイル: default.py プロジェクト: sleep3r/elogs
def ShiftTimeline(x, y, title):
    """
    Timeline plot for data in shifts

    Parameters
    ----------
    x : list of numbers
        description
    y : list of Shifts
        description
    title: string
        graph title

    Returns
    -------
    fig : plotly figure
    """
    trace = go.Scatter(x=[shift.start_time for shift in x], y=y)
    xaxis = go.XAxis(
        showgrid=True,
        showline=True,
        showticklabels=True,
        ticktext=[
            str(shift.start_time) + f' Смена {shift.order}' for shift in x
        ],
        tickvals=[shift.start_time for shift in x],
    )

    layout = go.Layout(
        title=title,
        xaxis=xaxis,
    )

    return go.Figure(data=[trace], layout=layout)
コード例 #5
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)
コード例 #6
0
ファイル: plotters.py プロジェクト: NeuroDataDesign/lemur
    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)
コード例 #7
0
ファイル: plotters.py プロジェクト: NeuroDataDesign/lemur
 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)
コード例 #8
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
コード例 #9
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,
    )
コード例 #10
0
ファイル: plotters.py プロジェクト: karunkannan/pymeda
    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)
コード例 #11
0
ファイル: gensim_test.py プロジェクト: jb-diplom/UvA-Papers
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
コード例 #12
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
コード例 #13
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')
コード例 #14
0
ファイル: ztools_draw.py プロジェクト: xiyanxiyan11/quantBook
def drDF_mul_line(df,ftg='tmp/tmp_plotly.html',m_tkAng=-20,m_dtick=5,
                m_title='多周期分时数据',
                xlst=['t1','t5','t15','t30','t60']):
    xdat = pygo.Data([])
    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,
        ),
                       
    ) #lay = pygo.Layout( 

    fig = pygo.Figure(data=xdat, layout=lay)
    pyplt(fig,filename=ftg,show_link=False)
コード例 #15
0
def get_vertical_bar_layout(
    annotations, title='', width='370', height='400',
    x_axis_title='', y_axis_title='',
    left=30, r=20, t=30, b=60,
):
    return go.Layout(
        title=title,
        width=width,
        height=height,
        margin={
            'pad': 2,
            'l': left, 'r': r, 't': t, 'b': b,
        },
        xaxis=go.XAxis(
            title=x_axis_title,
            zeroline=False,
            showticklabels=True,
            fixedrange=True,
        ),
        yaxis=dict(
            title=y_axis_title,
            zeroline=False,
            showticklabels=False,
            fixedrange=True,
        ),
        annotations=annotations,
    #     shapes=shapes,
    )
コード例 #16
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
コード例 #17
0
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)
コード例 #18
0
ファイル: plotters.py プロジェクト: NeuroDataDesign/lemur
    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)
コード例 #19
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)
コード例 #20
0
ファイル: plotters.py プロジェクト: NeuroDataDesign/lemur
    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)
コード例 #21
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')) 
コード例 #22
0
ファイル: ztools_draw.py プロジェクト: wangyu204/kc_demo
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)
コード例 #23
0
ファイル: ztools_draw.py プロジェクト: wangyu204/kc_demo
def drDF_mul_xsub(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
    # vertical_spacing
    fig = tools.make_subplots(rows=2,
                              cols=1,
                              shared_xaxes=True,
                              horizontal_spacing=0.01)
    #
    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])
        fig.append_trace(r_xnam, 1, 1)
    #
    fig['layout'].update(
        #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,
        ),
    )  #lay = pygo.Layout(

    #xdat = pygo.Data([r_t1,r_t5,r_t15,r_t30,r_t60])
    #fig = pygo.Figure(data=xdat, layout=lay)
    fig.append_trace(r_vol, 2, 1)
    pyplt(fig, filename=ftg, show_link=False)
コード例 #24
0
ファイル: ztools_draw.py プロジェクト: wangyu204/kc_demo
def drDF_tickX(df,
               ftg='tmp/tmp_plotly.html',
               m_title='tick数据',
               sgnTim='xtim',
               sgnPrice='price'):
    r_price = pygo.Scatter(x=df[sgnTim], y=df[sgnPrice], name=sgnPrice)

    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,
        ),
    )  #lay = pygo.Layout(

    xdat = pygo.Data([r_price])
    fig = pygo.Figure(data=xdat, layout=lay)
    pyplt(fig, filename=ftg, show_link=False)
コード例 #25
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')
コード例 #26
0
    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)
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
コード例 #28
0
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)
コード例 #29
0
ファイル: ztools_draw.py プロジェクト: wangyu204/kc_demo
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)
コード例 #30
0
ファイル: cluster-test.py プロジェクト: friberger/kodamat
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)