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


Python graph_objects.Bar方法代码示例

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


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

示例1: performance_plot

# 需要导入模块: from plotly import graph_objects [as 别名]
# 或者: from plotly.graph_objects import Bar [as 别名]
def performance_plot(perf, title):
    formats = ['nbformat'] + JUPYTEXT_FORMATS
    mean = perf.groupby('implementation').mean().loc[formats]
    std = perf.groupby('implementation').std().loc[formats]
    data = [go.Bar(x=mean.index,
                   y=mean[col],
                   error_y=dict(
                       type='data',
                       array=std[col],
                       color=color,
                       thickness=0.5
                   ) if col != 'size' else dict(),
                   name=col,
                   yaxis={'read': 'y1', 'write': 'y2', 'size': 'y3'}[col])
            for col, color in zip(mean.columns, DEFAULT_PLOTLY_COLORS)]
    layout = go.Layout(title=title,
                       xaxis=dict(title='Implementation', anchor='y3'),
                       yaxis=dict(domain=[0.7, 1], title='Read (secs)'),
                       yaxis2=dict(domain=[0.35, .65], title='Write (secs)'),
                       yaxis3=dict(domain=[0, .3], title='Size')
                       )
    return go.Figure(data=data, layout=layout) 
开发者ID:mwouts,项目名称:jupytext,代码行数:24,代码来源:Benchmarking Jupytext.py

示例2: _create_figure

# 需要导入模块: from plotly import graph_objects [as 别名]
# 或者: from plotly.graph_objects import Bar [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

示例3: plot_score

# 需要导入模块: from plotly import graph_objects [as 别名]
# 或者: from plotly.graph_objects import Bar [as 别名]
def plot_score(all_scores):
    fig = go.Figure(data=go.Bar(y=all_scores))
    fig.write_html('DQN_CNN_Trend_figure.html') 
开发者ID:FitMachineLearning,项目名称:FitML,代码行数:5,代码来源:ATARI_DQN_CNN.py

示例4: plot_score

# 需要导入模块: from plotly import graph_objects [as 别名]
# 或者: from plotly.graph_objects import Bar [as 别名]
def plot_score(all_scores):
    fig = go.Figure(data=go.Bar(y=all_scores))
    fig.write_html('Trend_figure.html') 
开发者ID:FitMachineLearning,项目名称:FitML,代码行数:5,代码来源:Advantage_Actor_Critic.py

示例5: build_stack_bar_data

# 需要导入模块: from plotly import graph_objects [as 别名]
# 或者: from plotly.graph_objects import Bar [as 别名]
def build_stack_bar_data(values_counts: List[pd.Series]) -> List[go.Bar]:
        """Create data for plotly stack bar chart with consistent colors between
        bars. Each bar values have indexes unique to the bar, without any correlation
        to other bars.

        Args:
            values_counts: an array of value_counts series

        Returns:
            A list of Bar objects.
        """
        data: List[go.Bar] = []
        for vc in values_counts:
            data = data + [
                go.Bar(
                    x=[counts],
                    y=[vc.name],
                    name=str(value)[:30],
                    orientation="h",
                    opacity=0.6,
                    legendgroup=vc.name,
                    marker_color=COLORS[i % 10],
                )
                for i, (value, counts) in enumerate(vc.items())
            ]
        return data 
开发者ID:scrapinghub,项目名称:arche,代码行数:28,代码来源:result.py

示例6: update_data

# 需要导入模块: from plotly import graph_objects [as 别名]
# 或者: from plotly.graph_objects import Bar [as 别名]
def update_data(self, value):
        """Update the data of the plot efficiently.

        Args:
            value (int or float): The value to be displayed.
        """
        # NOTE: If called by Plotly event handler and in case of error, this won't visible in a notebook cell, but in logs!
        checks.assert_type(value, (int, float))

        # Update value range
        if self._value_range is None:
            self._value_range = value, value
        else:
            self._value_range = min(self._value_range[0], value), max(self._value_range[1], value)

        # Update traces
        with self.batch_update():
            indicator = self.data[0]
            if self._value_range is not None:
                indicator.gauge.axis.range = self._value_range
                if self._cmap_name is not None:
                    indicator.gauge.bar.color = rgb_from_cmap(self._cmap_name, value, self._value_range)
            indicator.delta.reference = indicator.value
            indicator.value = value


# ############# Bar ############# # 
开发者ID:polakowo,项目名称:vectorbt,代码行数:29,代码来源:basic.py

示例7: __init__

# 需要导入模块: from plotly import graph_objects [as 别名]
# 或者: from plotly.graph_objects import Bar [as 别名]
def __init__(self, x_labels, trace_names=None, data=None, trace_kwargs={}, **layout_kwargs):
        """Create an updatable bar plot.

        Args:
            x_labels (list of str): X-axis labels, corresponding to index in pandas.
            trace_names (str or list of str): Trace names, corresponding to columns in pandas.
            data (array_like): Data in any format that can be converted to NumPy.
            trace_kwargs (dict or list of dict): Keyword arguments passed to each `plotly.graph_objects.Bar`.
            **layout_kwargs: Keyword arguments for layout.
        Example:
            ```py
            vbt.Bar(['x', 'y'], trace_names=['a', 'b'], data=[[1, 2], [3, 4]])
            ```
            ![](/vectorbt/docs/img/Bar.png)
            """
        if isinstance(trace_names, str) or trace_names is None:
            trace_names = [trace_names]
        self._x_labels = x_labels
        self._trace_names = trace_names

        super().__init__()
        self.update_layout(**layout_kwargs)

        # Add traces
        for i, trace_name in enumerate(trace_names):
            bar = go.Bar(
                x=x_labels,
                name=trace_name,
                showlegend=trace_name is not None
            )
            bar.update(**(trace_kwargs[i] if isinstance(trace_kwargs, (list, tuple)) else trace_kwargs))
            self.add_trace(bar)

        if data is not None:
            self.update_data(data) 
开发者ID:polakowo,项目名称:vectorbt,代码行数:37,代码来源:basic.py

示例8: plot_cumulative_returns

# 需要导入模块: from plotly import graph_objects [as 别名]
# 或者: from plotly.graph_objects import Bar [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

示例9: create_figures

# 需要导入模块: from plotly import graph_objects [as 别名]
# 或者: from plotly.graph_objects import Bar [as 别名]
def create_figures(stats: List[Stat], name: str) -> List[go.FigureWidget]:
        if name == "Categories":
            data = Result.build_stack_bar_data(stats)
            layout = Result.get_layout("Category fields", len(stats))
            layout.barmode = "stack"
            return [go.FigureWidget(data, layout)]
        if name == "Anomalies":
            return [Result.build_box_subplots(stats[0])]
        figures = []
        for stat in stats:
            y = stat.index.values.astype(str)
            if isinstance(stat, pd.Series):
                colors = [COLORS[0] if v > 0 else COLORS[1] for v in stat.values]
                data = [
                    go.Bar(
                        x=stat.values,
                        y=y,
                        orientation="h",
                        opacity=0.7,
                        marker_color=colors,
                    )
                ]
            else:
                data = [
                    go.Bar(x=stat[c].values, y=y, orientation="h", opacity=0.7, name=c)
                    for c in stat.columns
                ]

            layout = Result.get_layout(stat.name, len(stat))
            layout.xaxis = go.layout.XAxis(
                range=np.array([min(stat.values.min(), 0), max(stat.values.max(), 1)])
                * 1.05
            )
            if stat.name.startswith("Coverage"):
                layout.xaxis.tickformat = ".2p"
            if stat.name == "Coverage for boolean fields":
                layout.barmode = "stack"
            if stat.name.startswith("Fields coverage"):
                layout.annotations = Result.make_annotations(stat)

            figures.append(go.FigureWidget(data, layout))
        return figures 
开发者ID:scrapinghub,项目名称:arche,代码行数:44,代码来源:result.py

示例10: plot

# 需要导入模块: from plotly import graph_objects [as 别名]
# 或者: from plotly.graph_objects import Bar [as 别名]
def plot(self,
             macd_trace_kwargs={},
             signal_trace_kwargs={},
             histogram_trace_kwargs={},
             fig=None,
             **layout_kwargs):
        """Plot `MACD.macd`, `MACD.signal` and `MACD.histogram`.

        Args:
            macd_trace_kwargs (dict): Keyword arguments passed to `plotly.graph_objects.Scatter` for `MACD.macd`.
            signal_trace_kwargs (dict): Keyword arguments passed to `plotly.graph_objects.Scatter` for `MACD.signal`.
            histogram_trace_kwargs (dict): Keyword arguments passed to `plotly.graph_objects.Bar` for `MACD.histogram`.
            fig (plotly.graph_objects.Figure): Figure to add traces to.
            **layout_kwargs: Keyword arguments for layout.
        Example:
            ```py
            macd[(10, 20, 30, False, True)].plot()
            ```

            ![](/vectorbt/docs/img/MACD.png)"""
        if self.wrapper.ndim > 1:
            raise Exception("You must select a column first")

        macd_trace_kwargs = merge_kwargs(dict(
            name=f'MACD ({self.name})'
        ), macd_trace_kwargs)
        signal_trace_kwargs = merge_kwargs(dict(
            name=f'Signal ({self.name})'
        ), signal_trace_kwargs)
        histogram_trace_kwargs = merge_kwargs(dict(
            name=f'Histogram ({self.name})',
            showlegend=False
        ), histogram_trace_kwargs)

        layout_kwargs = merge_kwargs(dict(bargap=0), layout_kwargs)
        fig = self.macd.vbt.tseries.plot(trace_kwargs=macd_trace_kwargs, fig=fig, **layout_kwargs)
        fig = self.signal.vbt.tseries.plot(trace_kwargs=signal_trace_kwargs, fig=fig, **layout_kwargs)

        # Plot histogram
        hist = self.histogram.values
        hist_diff = tseries.nb.diff_1d_nb(hist)
        marker_colors = np.full(hist.shape, np.nan, dtype=np.object)
        marker_colors[(hist > 0) & (hist_diff > 0)] = 'green'
        marker_colors[(hist > 0) & (hist_diff <= 0)] = 'lightgreen'
        marker_colors[hist == 0] = 'lightgrey'
        marker_colors[(hist < 0) & (hist_diff < 0)] = 'red'
        marker_colors[(hist < 0) & (hist_diff >= 0)] = 'lightcoral'

        histogram_bar = go.Bar(
            x=self.histogram.index,
            y=self.histogram.values,
            marker_color=marker_colors,
            marker_line_width=0
        )
        histogram_bar.update(**histogram_trace_kwargs)
        fig.add_trace(histogram_bar)

        return fig 
开发者ID:polakowo,项目名称:vectorbt,代码行数:60,代码来源:basic.py


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