[英]How to change histogram color with buttons in plotly (python)?
Inspired by this post 受这篇文章的启发
I would like to change the color of the bars, each time a button is clicked.每次单击按钮时,我想更改条形的颜色。 It seems that the color of the bars just can't be updated.似乎条形的颜色无法更新。 Does anyone have a hint on this?有人对此有提示吗? (Code below) (下面的代码)
dataset = pd.DataFrame(
{
"age": [19, 18, 28, 33, 32],
"bmi": [27.9, 33.77, 33.0, 22.705, 28.88],
"children": [0, 1, 3, 0, 0],
}
)
col_bins = {c: int(dataset[c].max() - dataset[c].min()) for c in dataset.columns}
fig = px.histogram(
x=dataset["age"], nbins=col_bins["age"], color_discrete_sequence=["darkred"]
)
fig.update_layout(
updatemenus=[
{
"buttons": [
{
"label": c,
"method": "update",
"args": [{"x": [dataset[c]], "nbinsx": bins}, {"xaxis.title": c}],
}
for c, bins in col_bins.items()
],
"direction": "right",
"type": "buttons",
"x": 1,
"y": 1.15,
}
],
xaxis_title="age",
title_text="Histograms",
)
I added another entry to {"x": [dataset[c]], "nbinsx": bins}
so that it looks like: {"x": [dataset[c]], "nbinsx": bins, "marker.color": [marker_colors[i]]}
where marker_colors
is a list of colors I defined.我向{"x": [dataset[c]], "nbinsx": bins}
添加了另一个条目,这样它看起来像: {"x": [dataset[c]], "nbinsx": bins, "marker.color": [marker_colors[i]]}
其中marker_colors
是我定义的 colors 的列表。 This forum post was a useful resource.这篇论坛帖子是一个有用的资源。
Full code:完整代码:
import pandas as pd
import plotly.express as px
dataset = pd.DataFrame(
{
"age": [19, 18, 28, 33, 32],
"bmi": [27.9, 33.77, 33.0, 22.705, 28.88],
"children": [0, 1, 3, 0, 0],
}
)
col_bins = {c: int(dataset[c].max() - dataset[c].min()) for c in dataset.columns}
marker_colors = ['#1f77b4','#ff7f0e','#2ca02c']
fig = px.histogram(
x=dataset["age"], nbins=col_bins["age"]
)
fig.update_layout(
updatemenus=[
{
"buttons": [
{
"label": c,
"method": "update",
"args": [
{"x": [dataset[c]], "nbinsx": bins, "marker.color": [marker_colors[i]]},
{'xaxis.title': c},
],
}
for i, (c, bins) in enumerate(col_bins.items())
],
"direction": "right",
"type": "buttons",
"x": 1,
"y": 1.15,
}
],
xaxis_title="age",
title_text="Histograms",
)
fig.show()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.