Reputation: 21
I am trying to create two plots with the same colour scheme for the categories. However the plots use different colour schemas and it seems like I can't get my head around to fix this:
.
How can I force the plotly to use the same colors for both graphs? I’d greatly appreciate any help!
Upvotes: 2
Views: 2650
Reputation: 31146
Define a discrete color map. In code below: c = dict(zip(df["emotion"].unique(), px.colors.qualitative.G10))
import pandas as pd
import numpy as np
import plotly.express as px
# create some data
df = pd.DataFrame({"date":np.random.choice(pd.date_range("1-sep-2020","31-Dec-2020"),300),
"emotion":np.random.choice(["positive","negative","anticipation","fear","trust"], 300)}).sort_values("date")
# map emotions to a color
c = dict(zip(df["emotion"].unique(), px.colors.qualitative.G10))
# bar chart
px.bar(
df.groupby(["date", "emotion"], as_index=False)
.size()
.rename(columns={"size": "count"}),
x="date",
y="count",
color="emotion",
color_discrete_map=c
).show()
# pie chart
px.pie(
df.groupby("emotion", as_index=False).agg(
perc=("date", lambda s: len(s) / len(df))
),
values="perc",
names="emotion",
color="emotion",
color_discrete_map=c
).show()
Upvotes: 3
Reputation: 116
The color_discrete_map
property of plotly.express
pie and bar chart can be used to set explicit color values for columns.
Example usage for Pie Chart:
import plotly.express as px
df = px.data.tips()
fig = px.pie(df, values='tip', names='day', color='day',
color_discrete_map={'Thur':'lightcyan',
'Fri':'cyan',
'Sat':'royalblue',
'Sun':'darkblue'})
fig.show()
Example usage for Bar Chart:
import plotly.express as px
df = px.data.gapminder().query("year == 2007")
fig = px.bar(df, y="continent", x="pop", color="continent", orientation="h", hover_name="country",
color_discrete_map={
"Europe": "red",
"Asia": "green",
"Americas": "blue",
"Oceania": "goldenrod",
"Africa": "magenta"},
title="Explicit color mapping")
fig.show()
Upvotes: 1