Python plotly.graph_objects.Bar() Examples

The following are 12 code examples of plotly.graph_objects.Bar(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module plotly.graph_objects , or try the search function .
Example #1
Source File: Benchmarking Jupytext.py    From jupytext with MIT License 6 votes vote down vote up
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) 
Example #2
Source File: plotly_stock_chart.py    From tensortrade with Apache License 2.0 5 votes vote down vote up
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 
Example #3
Source File: ATARI_DQN_CNN.py    From FitML with MIT License 5 votes vote down vote up
def plot_score(all_scores):
    fig = go.Figure(data=go.Bar(y=all_scores))
    fig.write_html('DQN_CNN_Trend_figure.html') 
Example #4
Source File: Advantage_Actor_Critic.py    From FitML with MIT License 5 votes vote down vote up
def plot_score(all_scores):
    fig = go.Figure(data=go.Bar(y=all_scores))
    fig.write_html('Trend_figure.html') 
Example #5
Source File: Advantage_Actor_Critic.py    From FitML with MIT License 5 votes vote down vote up
def plot_score(all_scores):
    fig = go.Figure(data=go.Bar(y=all_scores))
    fig.write_html('Trend_figure.html') 
Example #6
Source File: result.py    From arche with MIT License 5 votes vote down vote up
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 
Example #7
Source File: basic.py    From vectorbt with GNU General Public License v3.0 5 votes vote down vote up
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) 
Example #8
Source File: basic.py    From vectorbt with GNU General Public License v3.0 5 votes vote down vote up
def update_data(self, data):
        """Update the data of the plot efficiently.

        Args:
            data (array_like): Data in any format that can be converted to NumPy.

                Must be of shape (`x_labels`, `trace_names`).
        Example:
            ```py
            fig = pd.Series([1, 2], index=['x', 'y'], name='a').vbt.Bar()
            fig.update_data([2, 1])
            fig.show()
            ```
            ![](/vectorbt/docs/img/Bar_updated.png)
        """
        data = reshape_fns.to_2d(np.asarray(data))
        checks.assert_same_shape(data, self._x_labels, axis=(0, 0))
        checks.assert_same_shape(data, self._trace_names, axis=(1, 0))

        # Update traces
        with self.batch_update():
            for i, bar in enumerate(self.data):
                bar.y = data[:, i]
                if bar.marker.colorscale is not None:
                    bar.marker.color = data[:, i]


# ############# Scatter ############# # 
Example #9
Source File: returns_chart.py    From spectre with Apache License 2.0 4 votes vote down vote up
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() 
Example #10
Source File: result.py    From arche with MIT License 4 votes vote down vote up
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 
Example #11
Source File: basic.py    From vectorbt with GNU General Public License v3.0 4 votes vote down vote up
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 ############# # 
Example #12
Source File: basic.py    From vectorbt with GNU General Public License v3.0 4 votes vote down vote up
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