Plotly:如何为类别分配特定颜色?

7
我有一个电力发电混合物的熊猫数据框。因此,它由不同燃料的电力发电组成。我想为特定燃料分配特定的颜色。 enter image description here 在Matplotlib中,通过传递颜色列表,可以方便地将特定颜色分配给特定类别,例如:

df.plot(kind="bar",color=["red","green","yellow"] enter image description here

我无法像使用Plotly一样为绘图分配颜色。在Plotly中,为特定类别分配特定颜色的最佳方法是什么? enter image description here
2个回答

9

如果你想要为特定的燃料指定特定的颜色,那么只要你的数据集结构不变,color_discrete_sequence 就可以很好地工作。但是指定每个类别的颜色最好通过以下方式实现:

color_discrete_map = <dict>

而在您的情况下:

fig = px.bar(df, color_discrete_map= {'Coal': 'black',
                                      'Oil': 'grey',
                                      'Gas': 'blue'}
            )

这样做可以避免依赖变量的顺序来匹配所需颜色的顺序。

示例图(使用数据集与原图结构相同但不同)

enter image description here

完整代码

import plotly.express as px
import pandas as pd
df = px.data.stocks().set_index('date')
fig = px.bar(df, color_discrete_map= {'GOOG': 'black',
                                      'AAPL': 'grey',
                                      'AMZN': 'blue',
                                      'FB': 'green',
                                      'NFLX': 'red',
                                      'MSFT':'firebrick'}
            )
fig.show()

如需其他选项,请查看Plotly:如何使用plotly.graph_objects和plotly.express在图中定义颜色? 在那你将发现如何将颜色序列更改为您想要的任何内容,并通过color_discrete_map指定一些例外情况。


1
同意。这是最通用的方法。 - Derek O

2

从plotly express的颜色序列文档中,您应该能够使用参数color_discrete_sequence来明确定义颜色序列。尝试运行:

fig=px.bar(df1, title="Electricity generation mix of Germany in TwH (2000-2019)", color_discrete_sequence=["black","grey","lightgrey","red","rosybrown","blue","limegreen","yellow","forestgreen"])

谢谢。它对我有用。 - hbstha123

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接