【发布时间】:2021-09-13 10:37:06
【问题描述】:
【问题讨论】:
标签: python plotly data-visualization visualization plotly-python
【问题讨论】:
标签: python plotly data-visualization visualization plotly-python
plotly.express 饼图和条形图的color_discrete_map 属性可用于为列设置显式颜色值。
饼图的用法示例:
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()
条形图的示例用法:
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()
【讨论】:
定义一个离散的颜色图。在下面的代码中: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()
【讨论】: