【问题标题】:Plotly express - code for plotting different columns of a histogram with a dropdownPlotly express - 使用下拉菜单绘制直方图不同列的代码
【发布时间】:2021-09-04 16:14:46
【问题描述】:
目前,我正在使用以下代码将数据绘制为直方图。
import plotly.express as px
fig = px.histogram(df, x="col_1")
fig.show()
有没有办法让下拉菜单控制数据框的哪一列绘制在直方图中?还是没有办法用 plotly express 做到这一点?
在任何一种情况下,我都需要什么代码来实现这个功能?谢谢。
【问题讨论】:
标签:
python
plotly
plotly-express
【解决方案1】:
我不确定这在 plotly express 中是否可行。您可以一次添加一个跟踪,然后将按钮列表传递给update_layout 函数的updatemenus 参数,该函数控制每个跟踪的visible 参数。
这是一个使用 plotly 财务数据集的一些列的示例:
import plotly.graph_objects as go
import pandas as pd
# Load dataset
df = pd.read_csv(
"https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv")
df.columns = [col.replace("AAPL.", "") for col in df.columns]
df = df.set_index("Date")
df = df[["Open","High","Low","Close","Volume"]]
# Initialize figure
fig = go.Figure()
buttons = []
for col_name in df.columns:
## add traces
if col_name == "Open":
fig.add_trace(go.Scatter(
x=df.index,
y=df[col_name],
name=col_name,
visible=True
)
)
else:
fig.add_trace(go.Scatter(
x=df.index,
y=df[col_name],
name=col_name,
visible=False
)
)
## construct buttons
buttons.append(dict(
label=col_name,
method="update",
args=[{"visible": [col_name==col for col in df.columns]},
{"title": "Yahoo"}]))
buttons_list = list(buttons)
fig.update_layout(
updatemenus=[
dict(buttons=buttons_list)
])
fig.show()