如何在Plotly Express中为Series数据源的柱状图设置自定义颜色
解决Plotly Express柱状图仅单个颜色生效的问题
问题出在你没有指定color参数来区分不同的类别。Plotly Express会把所有柱子视为同一个数据系列,因此只会使用color_discrete_sequence列表中的第一个颜色。
方案1:将Series转为DataFrame并指定类别列
把Series转换为包含类别列和数值列的DataFrame,通过color参数绑定类别列,让Plotly识别每个独立类别:
import pandas as pd import plotly.express as px # 将Series转为带列名的DataFrame df = pd.Series([100,200,300,400],index=['Cat1','Cat2','Cat3','Cat4']).reset_index(name='value') colors=['green','yellow','red','blue'] fig = px.bar(df, x='index', y='value', color='index', color_discrete_sequence=colors) fig.show()
方案2:直接绑定color参数为索引
无需转换DataFrame,直接将color参数设置为df.index,让Plotly按索引区分每个柱子:
import pandas as pd import plotly.express as px df = pd.Series([100,200,300,400],index=['Cat1','Cat2','Cat3','Cat4']) colors=['green','yellow','red','blue'] fig = px.bar(x=df.index, y=df, color=df.index, color_discrete_sequence=colors) fig.show()
内容的提问来源于stack exchange,提问作者teq508
相关产品推荐
相关产品推荐

