简体   繁体   中英

Plotly Dash bar chart with dynamically changing bar width (or dynamically changing graphing frequencies)

I have a bar graph made using Plotly Dash that looks like below. I have daily data from 2006 to now (2021) which makes the bar width very small. I am wondering if there is any way to plot and show a lower frequency graph when viewing in a larger timeframe(Y2006-Y2021) but show a detailed, higher frequency graph in a smaller timeframe(say, 2020 Mar to 2020 June).

条形图输出

The solution I can think of now is to pre-process the data in Pandas before plotting, but it won't be dynamically changing when I zoom in. How can I graph a dynamic graph with changing graphing frequencies? Below is my code.

df_data = df_data.dropna(subset=['date'])
    df_data = df_data.groupby(['date'])[
        ['mean_s', 'positive', 'negative']].mean().reset_index().sort_values('date')

fig = go.Figure()
fig.add_trace(go.Bar(
        x=df_data['date'],
        y=100 * (df_data['positive']) / (df_data['positive'] + df_data['negative']),
        base=0,
        name='Positive',
        marker_color=colors['pos1']
        ))
fig.add_trace(go.Bar(
        x=df_data['date'],
        y=100 * (df_data['negative']) / (df_data['positive'] + df_data['negative']),
        base=-100 * (df_data['negative']) / (df_data['positive'] + df_data['negative']),
        name='Negative',
        marker_color=colors['neg1']
        ))```

Given your requirement is to zoom in / interact with the data, the clear answer is a rangeslider

import plotly.graph_objects as go
import pandas as pd
import numpy as np

s = 365 * 15
df = pd.DataFrame({"date": pd.date_range("1-jan-2008", periods=s),
                   "positive": np.random.uniform(0, 20, s),
                   "negative": np.random.uniform(0, -5, s),})

go.Figure([
    go.Bar(x=df["date"], y=df["positive"], name="positive", marker_color="green"),
    go.Bar(x=df["date"], y=df["negative"], name="negative", base=0, marker_color="red"),
    ]).update_layout(
    barmode="stack",
    xaxis={
        "range": [df.iloc[-200]["date"], df["date"].max()],
        "rangeslider": {"visible": True},
    },
    margin={"l": 0, "r": 0, "t": 0, "r": 0},
)

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM