我根据训练集中每个班级的频率创建了以下直方图
numpy - 绘制43种不同类别的频率的一种可行方法-LMLPHP
每个类别的标签太长,类似于

Speed limit (20km/h)

我可以将每个标签放在条形上吗?

最佳答案

也许是这样的吗?

numpy - 绘制43种不同类别的频率的一种可行方法-LMLPHP

import numpy as np
import matplotlib.pyplot as plt

N=5
xlabel = ["Speed limit ("+str(i)+"km/h)" for i in range(0,N)]
xs = np.arange(0,7,1.5)
ys = [8,6,10,7,9]
width = 0.3*np.ones(N)

fig, ax = plt.subplots()
bars = ax.bar(xs, ys, width, color='k',alpha=0.3)
plt.xticks(xs, xlabel,rotation=270)

for i,bar in enumerate(bars):
    height = bar.get_height()
    ax.text(bar.get_x() + bar.get_width()/2., 0.1*height,
                '%s' % xlabel[i],rotation=90,ha='center', va='bottom')

plt.show()


要将其更改为水平条形图:

numpy - 绘制43种不同类别的频率的一种可行方法-LMLPHP

import numpy as np
import matplotlib.pyplot as plt

N = 5
xlabel = ["Speed limit ("+str(i)+"km/h)" for i in range(0,5)]
xs = np.arange(0,5)/2
ys = [8,6,10,7,9]
width = 0.3*np.ones(N)

fig, ax = plt.subplots()
bars = ax.barh(xs, ys, width, color='k',alpha=0.3)
plt.xticks([])

for i,bar in enumerate(bars):
    height = bar.get_height()
    ax.text(bar.get_x()+3, bar.get_y()+bar.get_height()/3,
                '%s' % xlabel[i],rotation=0,ha='center', va='bottom')
plt.tight_layout()
plt.show()

08-20 00:09