当前位置: 首页>>代码示例>>Python>>正文


Python subplots.make_subplots方法代码示例

本文整理汇总了Python中plotly.subplots.make_subplots方法的典型用法代码示例。如果您正苦于以下问题:Python subplots.make_subplots方法的具体用法?Python subplots.make_subplots怎么用?Python subplots.make_subplots使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在plotly.subplots的用法示例。


在下文中一共展示了subplots.make_subplots方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: _create_figure

# 需要导入模块: from plotly import subplots [as 别名]
# 或者: from plotly.subplots import make_subplots [as 别名]
def _create_figure(self, performance_keys):
        fig = make_subplots(
            rows=4, cols=1, shared_xaxes=True, vertical_spacing=0.03,
            row_heights=[0.55, 0.15, 0.15, 0.15],
        )
        fig.add_trace(go.Candlestick(name='Price', xaxis='x1', yaxis='y1',
                                     showlegend=False), row=1, col=1)
        fig.update_layout(xaxis_rangeslider_visible=False)

        fig.add_trace(go.Bar(name='Volume', showlegend=False,
                             marker={'color': 'DodgerBlue'}),
                      row=2, col=1)

        for k in performance_keys:
            fig.add_trace(go.Scatter(mode='lines', name=k), row=3, col=1)

        fig.add_trace(go.Scatter(mode='lines', name='Net Worth', marker={ 'color': 'DarkGreen' }),
                      row=4, col=1)

        fig.update_xaxes(linecolor='Grey', gridcolor='Gainsboro')
        fig.update_yaxes(linecolor='Grey', gridcolor='Gainsboro')
        fig.update_xaxes(title_text='Price', row=1)
        fig.update_xaxes(title_text='Volume', row=2)
        fig.update_xaxes(title_text='Performance', row=3)
        fig.update_xaxes(title_text='Net Worth', row=4)
        fig.update_xaxes(title_standoff=7, title_font=dict(size=12))

        self.fig = go.FigureWidget(fig)
        self._price_chart = self.fig.data[0]
        self._volume_chart = self.fig.data[1]
        self._performance_chart = self.fig.data[2]
        self._net_worth_chart = self.fig.data[-1]

        self.fig.update_annotations({'font': {'size': 12}})
        self.fig.update_layout(template='plotly_white', height=self._height, margin=dict(t=50))
        self._base_annotations = self.fig.layout.annotations 
开发者ID:tensortrade-org,项目名称:tensortrade,代码行数:38,代码来源:plotly_stock_chart.py

示例2: update_runtime_diff

# 需要导入模块: from plotly import subplots [as 别名]
# 或者: from plotly.subplots import make_subplots [as 别名]
def update_runtime_diff(start_date, end_date, funcs):
    if type(funcs) is str:
        funcs = [funcs]
    start_df = func_df[func_df["date"] == start_date]
    end_df = func_df[func_df["date"] == end_date]

    fig = make_subplots(
        rows=len(funcs), cols=1, specs=[[{"type": "domain"}] for _ in range(len(funcs))]
    )
    for i, func in enumerate(funcs):
        runtime = end_df[end_df["function"] == func]["runtime crypten"]
        runtime_prev = start_df[start_df["function"] == func]["runtime crypten"]
        func_text = func.capitalize()

        fig.add_trace(
            go.Indicator(
                mode="number+delta",
                value=float(runtime),
                title={
                    "text": f"{func_text}<br><span style='font-size:0.8em;color:gray'>"
                    + "runtime in seconds</span><br>"
                },
                delta={
                    "reference": float(runtime_prev),
                    "relative": True,
                    "increasing": {"color": "#ff4236"},
                    "decreasing": {"color": "#008000"},
                },
            ),
            row=i + 1,
            col=1,
        )
    fig.update_layout(height=300 * len(funcs))

    return fig 
开发者ID:facebookresearch,项目名称:CrypTen,代码行数:37,代码来源:app.py

示例3: update_error_diff

# 需要导入模块: from plotly import subplots [as 别名]
# 或者: from plotly.subplots import make_subplots [as 别名]
def update_error_diff(start_date, end_date, funcs):
    if type(funcs) is str:
        funcs = [funcs]
    start_df = func_df[func_df["date"] == start_date]
    end_df = func_df[func_df["date"] == end_date]

    fig = make_subplots(
        rows=len(funcs), cols=1, specs=[[{"type": "domain"}] for _ in range(len(funcs))]
    )
    for i, func in enumerate(funcs):
        error = end_df[end_df["function"] == func]["total abs error"]
        error_prev = start_df[start_df["function"] == func]["total abs error"]
        func_text = func.capitalize()

        fig.add_trace(
            go.Indicator(
                mode="number+delta",
                value=float(error),
                title={
                    "text": f"{func_text}<br><span style='font-size:0.8em;color:gray'>"
                    + "total abs error</span><br>"
                },
                delta={
                    "reference": float(error_prev),
                    "relative": True,
                    "increasing": {"color": "#ff4236"},
                    "decreasing": {"color": "#008000"},
                },
            ),
            row=i + 1,
            col=1,
        )
    fig.update_layout(height=300 * len(funcs))

    return fig 
开发者ID:facebookresearch,项目名称:CrypTen,代码行数:37,代码来源:app.py

示例4: build_box_subplots

# 需要导入模块: from plotly import subplots [as 别名]
# 或者: from plotly.subplots import make_subplots [as 别名]
def build_box_subplots(stat: pd.DataFrame) -> go.Figure:
        """Create a figure with box subplots showing fields coverages for jobs.

        Args:
            stat: a dataframe with field coverages

        Returns:
            A figure with box subplots
        """
        stat = stat.drop(columns=["std", "mean", "target deviation"])
        traces = [
            go.Box(
                y=row[1],
                name=row[0],
                boxpoints="all",
                jitter=0.3,
                boxmean="sd",
                hoverinfo="y",
            )
            for row in stat.iterrows()
        ]
        cols = 4
        rows = math.ceil(len(stat) / cols)
        fig = make_subplots(rows=rows, cols=cols)
        x = 0
        for i, j in itertools.product(range(1, rows + 1), range(1, cols + 1)):
            if x == len(traces):
                break
            fig.append_trace(traces[x], i, j)
            x += 1

        fig.update_layout(height=rows * 300 + 200, width=cols * 300, showlegend=False)
        fig.update_yaxes(tickformat=".4p")
        return fig 
开发者ID:scrapinghub,项目名称:arche,代码行数:36,代码来源:result.py

示例5: plot3Dgrid

# 需要导入模块: from plotly import subplots [as 别名]
# 或者: from plotly.subplots import make_subplots [as 别名]
def plot3Dgrid(rows, cols, viz_data, style, normalize=True, title=None):
    if len(viz_data) > rows * cols:
        raise ValueError('Number of plot data is more than the specified rows and columns.')
    fig = subplots.make_subplots(rows, cols, specs=[[{'is_3d': True}] * cols] * rows, print_grid=False)

    if style == 'flat':
        layout_3D = dict(
            xaxis=dict(range=[0, 360]),
            yaxis=dict(range=[0, 181]),
            aspectmode='manual',
            aspectratio=dict(x=3.6, y=1.81, z=1)
        )
    else:
        layout_3D = dict(
            xaxis=dict(range=[-1, 1]),
            yaxis=dict(range=[-1, 1]),
            zaxis=dict(range=[-1, 1]),
            aspectmode='cube'
        )

    rows, cols = _np.mgrid[1:rows + 1, 1: cols + 1]
    rows = rows.flatten()
    cols = cols.flatten()
    for IDX in range(0, len(viz_data)):
        cur_row = int(rows[IDX])
        cur_col = int(cols[IDX])
        fig.add_trace(genVisual(viz_data[IDX], style=style, normalize=normalize), cur_row, cur_col)
        fig.layout[f'scene{IDX + 1:d}'].update(layout_3D)

    if title is not None:
        fig.layout.update(title=title)
        filename = f'{title}.html'
    else:
        filename = f'{current_time()}.html'

    if env_info() == 'jupyter_notebook':
        plotly_off.iplot(fig)
    else:
        plotly_off.plot(fig, filename=filename) 
开发者ID:AppliedAcousticsChalmers,项目名称:sound_field_analysis-py,代码行数:41,代码来源:plot.py

示例6: plot_experiment

# 需要导入模块: from plotly import subplots [as 别名]
# 或者: from plotly.subplots import make_subplots [as 别名]
def plot_experiment(experiment_spec, experiment_df, metrics_cols):
    '''
    Plot the metrics vs. specs parameters of an experiment, where each point is a trial.
    ref colors: https://plot.ly/python/heatmaps-contours-and-2dhistograms-tutorial/#plotlys-predefined-color-scales
    '''
    y_cols = metrics_cols
    x_cols = ps.difference(experiment_df.columns.tolist(), y_cols + ['trial'])
    fig = subplots.make_subplots(rows=len(y_cols), cols=len(x_cols), shared_xaxes=True, shared_yaxes=True, print_grid=False)
    strength_sr = experiment_df['strength']
    min_strength, max_strength = strength_sr.min(), strength_sr.max()
    for row_idx, y in enumerate(y_cols):
        for col_idx, x in enumerate(x_cols):
            x_sr = experiment_df[x]
            guard_cat_x = x_sr.astype(str) if x_sr.dtype == 'object' else x_sr
            trace = go.Scatter(
                y=experiment_df[y], yaxis=f'y{row_idx+1}',
                x=guard_cat_x, xaxis=f'x{col_idx+1}',
                showlegend=False, mode='markers',
                marker={
                    'symbol': 'circle-open-dot', 'color': strength_sr, 'opacity': 0.5,
                    # dump first portion of colorscale that is too bright
                    'cmin': min_strength - 0.5 * (max_strength - min_strength), 'cmax': max_strength,
                    'colorscale': 'YlGnBu', 'reversescale': False
                },
            )
            fig.add_trace(trace, row_idx + 1, col_idx + 1)
            fig.update_xaxes(title_text='<br>'.join(ps.chunk(x, 20)), zerolinewidth=1, categoryarray=sorted(guard_cat_x.unique()), row=len(y_cols), col=col_idx+1)
        fig.update_yaxes(title_text=y, rangemode='tozero', row=row_idx+1, col=1)
    fig.layout.update(
        title=f'experiment graph: {experiment_spec["name"]}',
        width=100 + 300 * len(x_cols), height=200 + 300 * len(y_cols))
    plot(fig)
    graph_prepath = experiment_spec['meta']['graph_prepath']
    save_image(fig, f'{graph_prepath}_experiment_graph.png')
    # save important graphs in prepath directly
    prepath = experiment_spec['meta']['prepath']
    save_image(fig, f'{prepath}_experiment_graph.png')
    return fig 
开发者ID:kengz,项目名称:SLM-Lab,代码行数:40,代码来源:viz.py

示例7: plot_components_plotly

# 需要导入模块: from plotly import subplots [as 别名]
# 或者: from plotly.subplots import make_subplots [as 别名]
def plot_components_plotly(
        m, fcst, uncertainty=True, plot_cap=True, figsize=(900, 200)):
    """Plot the Prophet forecast components using Plotly.
    See plot_plotly() for Plotly setup instructions

    Will plot whichever are available of: trend, holidays, weekly
    seasonality, yearly seasonality, and additive and multiplicative extra
    regressors.

    Parameters
    ----------
    m: Prophet model.
    fcst: pd.DataFrame output of m.predict.
    uncertainty: Optional boolean to plot uncertainty intervals, which will
        only be done if m.uncertainty_samples > 0.
    plot_cap: Optional boolean indicating if the capacity should be shown
        in the figure, if available.
    figsize: Set the size for the subplots (in px).

    Returns
    -------
    A Plotly Figure.
    """

    # Identify components to plot and get their Plotly props
    components = {}
    components['trend'] = get_forecast_component_plotly_props(
        m, fcst, 'trend', uncertainty, plot_cap)
    if m.train_holiday_names is not None and 'holidays' in fcst:
        components['holidays'] = get_forecast_component_plotly_props(
            m, fcst, 'holidays', uncertainty)

    regressors = {'additive': False, 'multiplicative': False}
    for name, props in m.extra_regressors.items():
        regressors[props['mode']] = True
    for mode in ['additive', 'multiplicative']:
        if regressors[mode] and 'extra_regressors_{}'.format(mode) in fcst:
            components['extra_regressors_{}'.format(mode)] = get_forecast_component_plotly_props(
                m, fcst, 'extra_regressors_{}'.format(mode))
    for seasonality in m.seasonalities:
        components[seasonality] = get_seasonality_plotly_props(m, seasonality)

    # Create Plotly subplot figure and add the components to it
    fig = make_subplots(rows=len(components), cols=1, print_grid=False)
    fig['layout'].update(go.Layout(
        showlegend=False,
        width=figsize[0],
        height=figsize[1] * len(components)
    ))
    for i, name in enumerate(components):
        if i == 0:
            xaxis = fig['layout']['xaxis']
            yaxis = fig['layout']['yaxis']
        else:
            xaxis = fig['layout']['xaxis{}'.format(i + 1)]
            yaxis = fig['layout']['yaxis{}'.format(i + 1)]
        xaxis.update(components[name]['xaxis'])
        yaxis.update(components[name]['yaxis'])
        for trace in components[name]['traces']:
            fig.append_trace(trace, i + 1, 1)
    return fig 
开发者ID:facebook,项目名称:prophet,代码行数:63,代码来源:plot.py

示例8: __init__

# 需要导入模块: from plotly import subplots [as 别名]
# 或者: from plotly.subplots import make_subplots [as 别名]
def __init__(
        self,
        zmin=None,
        zmax=None,
        well=None,
        surfaces=None,
        sampling=5,
        nextend=5,
        zonelogshift=0,
        surfacenames=None,
        surfacecolors=None,
        cube=None,
        grid=None,
        gridproperty=None,
        zunit="",
        show_marginal=False,
    ):

        self._data = []
        self._figure = make_subplots(
            rows=2 if show_marginal else 1,
            cols=1,
            shared_xaxes=True,
            vertical_spacing=0,
            row_heights=[0.05, 0.95] if show_marginal else [1],
        )
        self._zmin = zmin if zmin else well.dataframe["Z_TVDSS"].min()
        self._zmax = zmax if zmax else well.dataframe["Z_TVDSS"].max()
        self._well = well
        self._nextend = nextend
        self._sampling = sampling
        self._surfaces = surfaces
        self._surfacenames = surfacenames
        self._surfacecolors = (
            surfacecolors
            if surfacecolors is not None
            else [
                "#1f77b4",  # muted blue
                "#ff7f0e",  # safety orange
                "#2ca02c",  # cooked asparagus green
                "#d62728",  # brick red
                "#9467bd",  # muted purple
                "#8c564b",  # chestnut brown
                "#e377c2",  # raspberry yogurt pink
                "#7f7f7f",  # middle gray
                "#bcbd22",  # curry yellow-green
                "#17becf",  # blue-teal
            ]
        )
        self.zunit = zunit
        self.show_marginal = show_marginal
        self.main_trace_row = 2 if show_marginal else 1
        self._cube = cube
        self._grid = grid
        self._gridproperty = gridproperty
        self._zonelogshift = zonelogshift

        self._fence = None 
开发者ID:equinor,项目名称:webviz-subsurface,代码行数:60,代码来源:xsection.py

示例9: make_distribution_plot

# 需要导入模块: from plotly import subplots [as 别名]
# 或者: from plotly.subplots import make_subplots [as 别名]
def make_distribution_plot(df, parameter, response, theme):
    """Make plotly traces for scatterplot and histograms for selected
    response and input parameter"""

    real_text = [f"Realization:{r}" for r in df["REAL"]]
    fig = make_subplots(
        rows=4,
        cols=2,
        specs=[
            [{"colspan": 2, "rowspan": 2}, None],
            [None, None],
            [{"rowspan": 2}, {"rowspan": 2}],
            [None, None],
        ],
    )
    fig.add_trace(
        {
            "type": "scatter",
            "showlegend": False,
            "mode": "markers",
            "x": df[parameter],
            "y": df[response],
            "text": real_text,
        },
        1,
        1,
    )
    fig.add_trace(
        {"type": "histogram", "x": df[parameter], "showlegend": False,}, 3, 1,
    )
    fig.add_trace(
        {"type": "histogram", "x": df[response], "showlegend": False,}, 3, 2,
    )
    fig["layout"].update(
        theme_layout(
            theme,
            {
                "height": 800,
                "bargap": 0.05,
                "xaxis": {"title": parameter,},
                "yaxis": {"title": response},
                "xaxis2": {"title": parameter},
                "xaxis3": {"title": response},
                "title": f"Distribution of {response} and {parameter}",
            },
        )
    )
    fig["layout"]["font"].update({"size": 8})
    return fig 
开发者ID:equinor,项目名称:webviz-subsurface,代码行数:51,代码来源:_parameter_response_correlation.py

示例10: alignment_reads_status

# 需要导入模块: from plotly import subplots [as 别名]
# 或者: from plotly.subplots import make_subplots [as 别名]
def alignment_reads_status (self,
        colors:list=["#f44f39","#fc8161","#fcaf94","#828282"],
        width:int= None,
        height:int=500,
        plot_title:str="Summary of reads alignment status"):
        """
        Plot a basic alignment summary
        * colors
            List of colors (hex, rgb, rgba, hsl, hsv or any CSS named colors https://www.w3.org/TR/css-color-3/#svg-color
        * width
            With of the plotting area in pixel
        * height
            height of the plotting area in pixel
        * plot_title
            Title to display on top of the plot
        """
        # Verify that alignemnt information are available
        if not self.has_alignment:
            raise pycoQCError ("No Alignment information available")
        self.logger.info ("\t\tComputing plot")

        df = self.alignments_df
        # Create empty multiplot figure
        fig = make_subplots(rows=1, cols=2, column_widths=[0.4, 0.6], specs=[[{"type": "table"},{"type": "pie"}]])

        # plot Table
        data = go.Table(
            columnwidth = [3,2,2],
            header = {"values":list(df.columns), "align":"center", "fill_color":"grey", "font_size":14, "font_color":"white", "height":40},
            cells = {"values":df.values.T , "align":"center", "fill_color":"whitesmoke", "font_size":12, "height":30})
        fig.add_trace (data, row=1, col=1)

        # plot Pie plot
        data = go.Pie (
            labels=df["Alignments"],
            values=df["Counts"],
            sort=False,
            marker={"colors":colors},
            name="Pie plot",
            textinfo='label+percent')
        fig.add_trace (data, row=1, col=2)

        # Change the layout
        fig.update_layout(
            width = width,
            height = height,
            title = {"text":plot_title, "xref":"paper" ,"x":0.5, "xanchor":"center"})

        return fig

    #~~~~~~~ALIGNMENT RATE METHOD AND HELPER~~~~~~~# 
开发者ID:a-slide,项目名称:pycoQC,代码行数:53,代码来源:pycoQC_plot.py

示例11: plot_cumulative_returns

# 需要导入模块: from plotly import subplots [as 别名]
# 或者: from plotly.subplots import make_subplots [as 别名]
def plot_cumulative_returns(returns, positions, transactions, benchmark, annual_risk_free):
    from ..trading import turnover, sharpe_ratio, drawdown, annual_volatility

    import plotly.graph_objects as go
    import plotly.subplots as subplots

    fig = subplots.make_subplots(specs=[[{"secondary_y": True}]])

    cum_ret = (returns + 1).cumprod()
    fig.add_trace(go.Scatter(x=cum_ret.index, y=cum_ret.values * 100 - 100, name='portfolio',
                             hovertemplate='<b>Date</b>:%{x}<br><b>Return</b>: %{y:.3f}%'))
    fig.add_shape(go.layout.Shape(y0=0, y1=0, x0=cum_ret.index[0], x1=cum_ret.index[-1],
                                  type="line", line=dict(width=1)))

    if benchmark is not None:
        cum_bench = (benchmark + 1).cumprod()
        fig.add_trace(go.Scatter(x=cum_bench.index, y=cum_bench.values * 100 - 100,
                                 name='benchmark', line=dict(width=0.5)))

    fig.add_shape(go.layout.Shape(
        type="rect", xref="x", yref="paper", opacity=0.5, line_width=0,
        fillcolor="LightGoldenrodYellow", layer="below",
        y0=0, y1=1, x0=cum_ret.idxmax(), x1=cum_ret[cum_ret.idxmax():].idxmin(),
    ))

    to = turnover(positions, transactions) * 100
    resample = int(len(to) / 126)
    if resample > 0:
        to = to.fillna(0).rolling(resample).mean()[::resample]
    fig.add_trace(go.Bar(x=to.index, y=to.values, opacity=0.2, name='turnover'),
                  secondary_y=True)

    sr = sharpe_ratio(returns, annual_risk_free)
    dd, ddd = drawdown(cum_ret)
    mdd = abs(dd.min())
    mdd_dur = ddd.max()
    vol = annual_volatility(returns) * 100

    if benchmark is not None:
        bench_sr = sharpe_ratio(benchmark, annual_risk_free)
        bench_vol = annual_volatility(benchmark) * 100
    else:
        bench_sr = 0
        bench_vol = 0

    ann = go.layout.Annotation(
        x=0.01, y=0.98, xref="paper", yref="paper",
        showarrow=False, borderwidth=1, bordercolor='black', align='left',
        text="<b>Overall</b> (portfolio/benchmark)<br>"
             "SharpeRatio:      {:.3f}/{:.3f}<br>"
             "MaxDrawDown:  {:.2f}%, {} Days<br>"
             "AnnualVolatility: {:.2f}%/{:.2f}%</b>"
            .format(sr, bench_sr, mdd * 100, mdd_dur, vol, bench_vol),
    )

    fig.update_layout(height=400, annotations=[ann], margin={'t': 50})
    fig.update_xaxes(tickformat='%Y-%m-%d')
    fig.update_yaxes(title_text='cumulative return', ticksuffix='%', secondary_y=False)
    fig.update_yaxes(title_text='turnover', ticksuffix='%', secondary_y=True)
    fig.show() 
开发者ID:Heerozh,项目名称:spectre,代码行数:62,代码来源:returns_chart.py

示例12: plot

# 需要导入模块: from plotly import subplots [as 别名]
# 或者: from plotly.subplots import make_subplots [as 别名]
def plot(self, percentile=[], conf_interval=[], *args, **kwargs):
        """Plot Campbell Diagram.

        This method plots Campbell Diagram.

        Parameters
        ----------
        percentile : list, optional
            Sequence of percentiles to compute, which must be between
            0 and 100 inclusive.
        conf_interval : list, optional
            Sequence of confidence intervals to compute, which must be between
            0 and 100 inclusive.
        args: optional
            harmonics : list, optional
                List with the harmonics to be plotted.
                The default is to plot 1x.
        kwargs : optional
            Additional key word arguments can be passed to change the plot
            (e.g. line=dict(width=4.0, color="royalblue"), opacity=1.0, ...)
            *See Plotly Python Figure Reference for more information.

        Returns
        -------
        subplots : Plotly graph_objects.make_subplots()
            Plotly figure with diagrams for frequency and log dec.
        """
        fig0 = self.plot_nat_freq(percentile, conf_interval, *args, **kwargs)

        default_values = dict(showlegend=False)
        for k, v in default_values.items():
            kwargs.setdefault(k, v)

        fig1 = self.plot_log_dec(percentile, conf_interval, *args, **kwargs)

        subplots = make_subplots(rows=1, cols=2)
        for data in fig0["data"]:
            subplots.add_trace(data, 1, 1)
        for data in fig1["data"]:
            subplots.add_trace(data, 1, 2)

        subplots.update_xaxes(fig0.layout.xaxis, row=1, col=1)
        subplots.update_yaxes(fig1.layout.yaxis, row=1, col=1)
        subplots.update_xaxes(fig0.layout.xaxis, row=1, col=2)
        subplots.update_yaxes(fig1.layout.yaxis, row=1, col=2)
        subplots.update_layout(
            plot_bgcolor="white",
            width=1800,
            height=900,
            legend=dict(
                font=dict(family="sans-serif", size=14),
                bgcolor="white",
                bordercolor="black",
                borderwidth=2,
            ),
        )

        return subplots 
开发者ID:ross-rotordynamics,项目名称:ross,代码行数:60,代码来源:st_results.py


注:本文中的plotly.subplots.make_subplots方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。