Plotly: How to assign specific colors for categories? [duplicate]

回眸只為那壹抹淺笑 提交于 2021-02-08 05:55:22

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!