matplotlib中条形图的平均线

时间:2014-12-30 17:40:36

标签: python matplotlib plot

我们如何使用matplotlib绘制直方图的平均线(水平)?

现在,我能够毫无问题地绘制直方图。 以下是我使用的代码:

## necessary variables
ind = np.arange(N)                # the x locations for the groups
width = 0.2                      # the width of the bars
plt.tick_params(axis='both', which='major', labelsize=30)
plt.tick_params(axis='both', which='minor', labelsize=30)
ax2 = ax.twinx()
## the bars

rects1 = ax.bar(ind, PAAE1, width,
            color='0.2',
            error_kw=dict(elinewidth=2,ecolor='red'),
            label='PAAE1')

rects2 = ax.bar(ind+width, PAAE2, width,
                color='0.3',
                error_kw=dict(elinewidth=2,ecolor='black'),
                label='PAAE2')

rects3 = ax2.bar(ind+width+width, AAE1, width,
            color='0.4',
            error_kw=dict(elinewidth=2,ecolor='red'),
            label='AAE1')

rects4 = ax2.bar(ind+3*width, AAE2, width,
                color='0.5',
                error_kw=dict(elinewidth=2,ecolor='black'),
                       label='AAE3')



maxi = max(dataset[2])
maxi1 = max(dataset[4])
f_max = max(maxi, maxi1)
lns = [rects1,rects2,rects3,rects4]
labs = [l.get_label() for l in lns]


ax.legend(lns, labs, loc='upper center', ncol=4)

# axes and labels
ax.set_xlim(-width,len(ind)+width)
ax.set_ylim(0, 100)
ax.set_ylabel('PAAE', fontsize=25)
ax2.set_ylim(0, f_max+500)
ax2.set_ylabel('AAE (mW)', fontsize=25)
xTickMarks = dataset[0]
ax.set_xticks(ind+width)
xtickNames = ax.set_xticklabels(xTickMarks)
plt.setp(xtickNames, rotation=90, fontsize=25)

我想绘制PAAE 1,2和AAE 1,2的平均线。 我应该用什么来绘制平均线?

1 个答案:

答案 0 :(得分:13)

如果您想要一条垂直线来表示平均使用axvline(x_value)。这将放置一条始终跨越y轴的完整(或指定部分)的垂直线。水平线也有axhline

在其他作品中,您可能会遇到以下情况:

ax.axvline(data1.mean(), color='blue', linewidth=2)
ax.axvline(data2.mean(), color='green', linewidth=2)

作为一个更完整但不必要的复杂例子(大部分都是用曲线箭头很好地注释方法):

import numpy as np
import matplotlib.pyplot as plt

data1 = np.random.normal(0, 1, 1000)
data2 = np.random.normal(-2, 1.5, 1000)

fig, ax = plt.subplots()

bins = np.linspace(-10, 5, 50)
ax.hist(data1, bins=bins, color='blue', label='Dataset 1',
        alpha=0.5, histtype='stepfilled')
ax.hist(data2, bins=bins, color='green', label='Dataset 2',
        alpha=0.5, histtype='stepfilled')

ax.axvline(data1.mean(), color='blue', linewidth=2)
ax.axvline(data2.mean(), color='green', linewidth=2)

# Add arrows annotating the means:
for dat, xoff in zip([data1, data2], [15, -15]):
    x0 = dat.mean()
    align = 'left' if xoff > 0 else 'right'
    ax.annotate('Mean: {:0.2f}'.format(x0), xy=(x0, 1), xytext=(xoff, 15),
            xycoords=('data', 'axes fraction'), textcoords='offset points',
            horizontalalignment=align, verticalalignment='center',
            arrowprops=dict(arrowstyle='-|>', fc='black', shrinkA=0, shrinkB=0,
                            connectionstyle='angle,angleA=0,angleB=90,rad=10'),
            )

ax.legend(loc='upper left')
ax.margins(0.05)
plt.show()

enter image description here