在具有panda和matplotlib的Python上,使用bar_label将值标签插入数据框中的图时出错

zf9nrax1  于 2023-01-11  发布在  Python
关注(0)|答案(2)|浏览(139)

我尝试使用bar_label将值标签添加到matplotlib的绘图中。我的数据来自DataFrame。我收到错误AttributeError: 'AxesSubplot' object has no attribute 'datavalues'。我尝试在StackOverflow和其他地方查看类似问题的不同答案,但我仍然不明白如何解决这个问题。有人能给我指出正确的方向吗?
我的matplotlib版本是3.6.0,所以这不是问题所在。
如果我尝试从一个列表构建它,如下面的例子,它工作正常,并生成了带有我想要的值标签的图。

year = [1999, 2000, 2001]
animals = [40, 50, 10]

barplot = plot.bar(year,
                   animals,
                   fc = "lightgray",
                   ec = "black")

plt.bar_label(container = barplot, labels = y, label_type = "center")

plt.show()

问题是当我试图从DataFrame中获取值的时候。例如,下面的代码:

year_v2 = [1999, 2010, 2011]
animals_v2 = [400, 500, 100]

df_v2 = pd.DataFrame([year_v2, animals_v2], index = ["year", "animals"]).T

barplot_v2 = df_v2.plot.bar("year",
                            "animals",
                            fc = "lightgray",
                            ec = "black")

plt.bar_label(container = barplot_v2,
              labels = "animals",
              label_type = "center")

plt.show()

生成图,但不带值标签,并带有错误AttributeError: 'AxesSubplot' object has no attribute 'datavalues'

km0tfn4u

km0tfn4u1#

您需要使用axessubplot中的bar_label访问轴中的容器:

year_v2 = [1999, 2010, 2011]
animals_v2 = [400, 500, 100]

df_v2 = pd.DataFrame([year_v2, animals_v2], index = ["year", "animals"]).T

barplot_v2 = df_v2.plot.bar("year",
                            "animals",
                            fc = "lightgray",
                            ec = "black")

barplot_v2.bar_label(container = barplot_v2.containers[0],
              labels = animals_v2,
              label_type = "center")

plt.show()

输出:

jexiocij

jexiocij2#

建议:

您可以尝试使用matplotlib.plyplot.text()方法向图表添加数值标签。该方法具有以下参数。

matplotlib.plyplot.text(x, y, s, ha, Bbox)

x,y = coordinates of the plot
s = String to be displayed
ha = Horizontal alignment
Bbox = the rectangular box around the text

样品代码:

import matplotlib.pyplot as plt
import pandas as pd

year_v2 = [1999, 2010, 2011]
animals_v2 = [400, 500, 100]

df_v2 = pd.DataFrame([year_v2, animals_v2], index = ["year", "animals"]).T

barplot_v2 = df_v2.plot.bar("year","animals",fc = "lightgray",ec = "black")

def valuelabel(x,y):
    for i in range(len(x)):
        plt.text(i,y[i],y[i], ha = 'center')
        
valuelabel(df_v2.year,df_v2.animals)

plt.show()

输出:

参考文献:

https://www.geeksforgeeks.org/adding-value-labels-on-a-matplotlib-bar-chart/https://pythonguides.com/matplotlib-bar-chart-labels/

相关问题