Plotly:如何为类别分配特定的颜色?
Plotly: How to assign specific colors for categories?
我有一个 pandas 发电组合数据框。所以它包括不同燃料的发电。我想为特定燃料分配特定颜色。
在 Matplotlib 中,通过传递颜色列表将特定颜色分配给特定类别很方便,例如
df.plot(kind="bar",color=["red","green","yellow"]
我无法使用 Plotly 为绘图分配类似的颜色。将特定颜色分配给 Plotly 中特定类别的最佳方法是什么?
从 plotly express 中的 documentation on color sequences,您应该能够使用参数 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"])
如果您打算为特定燃料分配特定颜色,那么color_discrete_sequence
可能适用于只要你的数据集的结构永远不会改变。但是最好通过以下方式为每个类别指定颜色:
color_discrete_map = <dict>
在你的情况下:
fig = px.bar(df, color_discrete_map= {'Coal': 'black',
'Oil': 'grey',
'Gas': 'blue'}
)
这样您就不必依赖变量序列来匹配所需颜色的序列。
示例图(具有不同但结构相同的数据集)
完整代码
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()
其他选项请查看?在那里你会发现如何将颜色序列更改为任何你想要的,并且仍然通过 color_discrete_map
.
指定一些例外。
我有一个 pandas 发电组合数据框。所以它包括不同燃料的发电。我想为特定燃料分配特定颜色。
df.plot(kind="bar",color=["red","green","yellow"]
我无法使用 Plotly 为绘图分配类似的颜色。将特定颜色分配给 Plotly 中特定类别的最佳方法是什么?
从 plotly express 中的 documentation on color sequences,您应该能够使用参数 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"])
如果您打算为特定燃料分配特定颜色,那么color_discrete_sequence
可能适用于只要你的数据集的结构永远不会改变。但是最好通过以下方式为每个类别指定颜色:
color_discrete_map = <dict>
在你的情况下:
fig = px.bar(df, color_discrete_map= {'Coal': 'black',
'Oil': 'grey',
'Gas': 'blue'}
)
这样您就不必依赖变量序列来匹配所需颜色的序列。
示例图(具有不同但结构相同的数据集)
完整代码
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()
其他选项请查看color_discrete_map
.