Python Plotly:使用文本标注多个变量

3

我正在尝试在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

对于每个条形图,我想看到月份和销售额,类似于“1月-543”,“2月-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)

或者按照以下方式进行月份,但我无法将两者合并

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)

非常感谢任何帮助


你可以跳过 pio.show(barchart) - rpanai
1个回答

4

我认为这更是一个Pandas的问题而非Plotly的问题。你可以创建一个包含所需文本输出的列,并将其传递给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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接