首页 > 解决方案 > 如何注释下图?

问题描述

我使用 3 个不同的熊猫系列制作了直方图。我想标记条形组 1、2 和 3。我没有成功使用 xlabels 来执行此操作;从技术上讲,它可以工作,但数字 1、2、3 没有与条正确对齐。

我决定跳过它并尝试注释。不幸的是,我知道如何正确地做到这一点。

我尝试使用 xlabels,但未成功。现在我正在尝试注释,但我无法在图表上显示多个文本。

以下是数据的示例 Wr_Spr_Conv = [1,1,1,2,2,2,3,3,3,2,2,1,2,3...]

new2['Wr_Spr_Conv'].replace(0, pd.np.nan).dropna(inplace = True)
new2['Re_Spr_Conv'].replace(0, pd.np.nan).dropna(inplace = True)
new2['Ma_Spr_Conv'].replace(0, pd.np.nan).dropna(inplace = True)


plt.style.use('seaborn')
x_labels = [1,2,3]
fig, ax1 = plt.subplots(figsize=(10,10))

#ax1.spines['left'].set_position(('outward', 10))
#ax1.spines['bottom'].set_position(('outward', 10))
# Hide the right and top spines

ax1.spines['right'].set_visible(False)
ax1.spines['top'].set_visible(False)
ax1.spines['bottom'].set_visible(False)
ax1.spines['right'].set_visible(False)
nbins = 9
ax1.tick_params(bottom="off", top="off", left="off", right="off")
    ax1.hist([new2['Wr_Spr_Conv'],new2['Re_Spr_Conv'],new2['Ma_Spr_Conv']],nbins)
#ax1.set_xticks(3)
#ax1.set_xticks(3)
#ax1.set_xlim(right =3)
#ax1.set_xlim(left=0)
# Only show ticks on the left and bottom spines
#ax1.yaxis.set_ticks_position('left')
#ax1.xaxis.set_ticks_position('bottom')    
ax1.set_xticks(x_labels)
ax1.set_xlim(right=3)  # adjust the right leaving left unchanged
ax1.set_xlim(left=1)  # adjust the left leaving right unchanged
ax1.xaxis.set_major_locator(MaxNLocator(integer=True))
#ax1.annotate('Level 1',xy=(1,15))

标签: pythonmatplotlibgraphannotations

解决方案


假设你Wr_Spr_Convpandas.Series,你可以使用value_countspyplot 的bar方法和属性align='center'来创建一个带有预定义数量的 bin 和 centered labels的直方图。

这是一个最小的例子:

import pandas as pd
from matplotlib import pyplot as plt

nbr_bins = 9
Wr_Spr_Conv = pd.Series( [1,1,1,2,2,5,9,2,7,7,2,3,3,3,2,2,1,2,3]) 
vc = Wr_Spr_Conv.value_counts(bins=nbr_bins)
plt.bar(vc.index.mid, vc.values, width=0.9*vc.index.length[0], align='center')
plt.gca().set_xticks(vc.index.mid)
plt.show()

结果: 在此处输入图像描述

这应该让你开始!


推荐阅读