我想使用 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/