问题
I have a pandas dataframe of electricity generation mix. So it consists of electricity generation by different fuels. I want to assign a specific color to a specific fuel. In Matplotlib, it is convenient to assign a specific color to a specific category by passing a list of colors, e.g.
df.plot(kind="bar",color=["red","green","yellow"]
I wasn't able to assign color similarly for plots using Plotly. What would be the best way to assign specific color to specific categories in Plotly?
回答1:
From the documentation on color sequences in plotly express, you should be able to explicitly define a color sequence using the parameter color_discrete_sequence
. Try running:
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"])
回答2:
If you're aiming to assign a specific color to a specific fuel then color_discrete_sequence
may work just fine for you as long as the structure of your dataset never changes. But the way to specify a color per category is best done through:
color_discrete_map = <dict>
And in your case:
fig = px.bar(df, color_discrete_map= {'Coal': 'black',
'Oil': 'grey',
'Gas': 'blue'}
)
This way you won't have to rely on the sequence of variables to match the sequence of your desired colors.
Example plot (with a different but structurally identical dataset)
Complete code
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()
For other options please take a look at Plotly: How to define colors in a figure using plotly.graph_objects and plotly.express?? There you will find how to change the color sequence to whatever you want and still specify som exceptions through color_discrete_map
.
来源:https://stackoverflow.com/questions/65706720/plotly-how-to-assign-specific-colors-for-categories