gpt4 book ai didi

Python Plotly 用文本注释多个变量

转载 作者:行者123 更新时间:2023-12-04 09:00:57 25 4
gpt4 key购买 nike

我正在尝试在 plotly 中创建一个条形图,我希望 x 和 y 轴为空,而是在条形图本身上显示数据(我知道它包含在悬停中,但这是为了使用用于演示)。我在下面创建了一些虚拟数据。

import random
import pandas as pd
import plotly.express as px

months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"]
years = [2018,2019,2020]
sales = random.sample(range(10000),18)

df = pd.DataFrame(columns = ["Year", "Month", "Sales"])

df["Year"]= years*6
df.sort_values("Year", inplace = True)
df["Month"] = months*3
df["Sales"] = sales

对于每个条形图,我想查看月份和销售额,例如“Jan - 543”、“Feb - 1200”等。我可以将单个列中的值添加到条形图中,如下所示以下为销售

barchart = px.bar(
data_frame = df.groupby(["Month"]).Sales.sum().reset_index(),
x = "Sales",
y = "Month",
title = "Sales by Month 2018-2020",
orientation = "h",
barmode = "group",
text = "Sales"
)
barchart.update_xaxes(visible = False)
barchart.update_yaxes(visible = False)
pio.show(barchart)

或者按照下面的 Months 但我不能将两者结合起来

barchart = px.bar(
data_frame = df.groupby(["Month"]).Sales.sum().reset_index(),
x = "Sales",
y = "Month",
title = "Sales by Month 2018-2020",
orientation = "h",
barmode = "group",
text = "Month"
)
barchart.update_xaxes(visible = False)
barchart.update_yaxes(visible = False)
pio.show(barchart)

任何帮助将不胜感激

最佳答案

在我看来,这更像是一个 pandas 问题,而不是一个阴谋的问题。您可以使用给定的文本输出创建一个列并将其传递给 plotly.express

import pandas as pd
import plotly.express as px

grp = df.groupby(["Month"])["Sales"].sum().reset_index()
grp["Text"] = grp["Month"] + " - "+ grp["Sales"].astype(str)
print(grp)
  Month  Sales         Text
0 Apr 15949 Apr - 15949
1 Feb 12266 Feb - 12266
2 Jan 9734 Jan - 9734
3 Jun 13771 Jun - 13771
4 Mar 24007 Mar - 24007
5 May 12720 May - 12720

然后绘制grp

barchart = px.bar(
data_frame = grp,
x="Sales",
y="Month",
title="Sales by Month 2018-2020",
orientation ="h",
barmode="group",
text="Text")
barchart.update_xaxes(visible = False)
barchart.update_yaxes(visible = False)
barchart.update_layout(title_x=0.5)

enter image description here

关于Python Plotly 用文本注释多个变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63568096/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com