Plotly:更改图例标签并聚合数值
Posted
技术标签:
【中文标题】Plotly:更改图例标签并聚合数值【英文标题】:Plotly: Changing the legend labels and aggregating numerical values 【发布时间】:2021-12-18 16:29:15 【问题描述】:这是我的代码:
fig = px.bar(
data_frame=dftotal,
x="YEAR",
y="OPINION",
title="Score des opinions par années",
color="OPINION",
width=1300,
height=700,
template='plotly_dark',
color_discrete_map=5: "green",4: "lightgreen",3: "yellow",2:"orange", 1: "red", "inconnu": "grey"
)
fig.update_layout(title_x=0.5)
fig.show()
它给出了这个结果:
但我想在 2014 年的每一年中实现如下所示的结果。我认为,通过将每个值获得的“总分”相加。
我还想更改图例的标签名称。类似于:“非常糟糕”而不是“OPINION=1”。
【问题讨论】:
【参考方案1】: 你没有提供样本数据,所以我模拟了它 counts 你可以使用直方图,我选择使用 pandasvalue_counts()
来生成用于绘图的摘要数据框
地图轨迹/图例名称。已使用https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.map.html 将 1、2、... 映射到“非常糟糕”、“糟糕”、... NB 使用 fillna()
表示“inconnu”
如果您想查看OPINION的原始值,也可以选择使用hover_data=["OPINION"]
import pandas as pd
import numpy as np
import plotly.express as px
dftotal = pd.DataFrame("YEAR":np.random.choice(range(2010,2021),10000), "OPINION":np.random.choice(range(1,6), 10000))
dftotal.loc[dftotal.sample(200).index, "OPINION"] = "inconnu"
dfp = dftotal.value_counts().reset_index().rename(columns=0:"COUNT").sort_values(["YEAR","OPINION"])
fig = px.bar(
data_frame=dfp,
x="YEAR",
y="COUNT",
title="Score des opinions par années",
color=dfp["OPINION"].map(1:"very bad",2:"bad", 3:"ok",4:"good",5:"very good").fillna("inconnu"),
# width=1300,
height=700,
template='plotly_dark',
color_discrete_map="very good": "green","good": "lightgreen","ok": "yellow","bad":"orange", "very bad": "red", "inconnu": "grey"
)
fig.update_layout(title_x=0.5)
【讨论】:
以上是关于Plotly:更改图例标签并聚合数值的主要内容,如果未能解决你的问题,请参考以下文章