python - 使用 pandas DataFrames 绘制条形图时如何添加 bin 内容的文本标签?

标签 python matplotlib pandas bar-chart

我想使用 pandas plot() 函数创建一个条形图,其中每个条形都有一个文本标签,显示它在视觉上代表的确切数字。

此外,我希望能够格式化标签,例如四舍五入到最接近的整数。

最佳答案

以防万一您还没有弄清楚,这里有一些工作代码将 Matplotlib API 与 pandas 以您正在寻找的方式进行绘图相结合。

import pandas as pd
import matplotlib.pyplot as plt

# Dummy data
x = range(1, 5)
y = [i**(0.5) for i in x]
ser = pd.Series(y, index=x)

ax1 = ser.plot(kind='bar')  # plot with pandas and assign to an axis object

# Grab the patches from the axis and plot the text near them, rounding to 1dp
for rect in ax1.patches:
    height = rect.get_height()
    ax1.text(rect.get_x()+rect.get_width()/2., 1.05*height, round(height, 1),
                ha='center', va='bottom')

关于python - 使用 pandas DataFrames 绘制条形图时如何添加 bin 内容的文本标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21435992/

相关文章:

python - 检测元素是否在成对的区间限制内

python - 将 pandas 列值转换为行

python - 如何在 Flask 蓝图中模拟.patch 函数?

python - 在 Django 中将消息显示为弹出窗口/警报?

python - 组合线性同余发生器

python - Matplotlib 散点图和颜色图的问题

python - 如何将 Pandas Dataframe 写入现有的 Django 模型

python - Geopandas - 在与多边形相交处分割线,在新链接属性中保留多边形 ID

python - 围绕 matplotlib 线绘制边框

python - python中的手动直方图