首页 > 解决方案 > 更改 x 轴标记 Matplotlib?

问题描述

我想明确地传递一个包含 0、1、2 等的列表作为 x 标签,而不是由 value counts 函数返回的内容。任何想法如何做到这一点?

df2 = idx_open.hour.value_counts(bins=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24]).sort_index()
df2.plot(kind='bar',color=['blue'],ax=ax)
ax.legend(['Öffnungen','Schließungen'])
plt.ylabel('Anzahl [-]')
plt.xlabel('Stunde des Tages')
plt.title(dateiname)

在此处输入图像描述

标签: pythonpandasmatplotlib

解决方案


您可以尝试使用xticks制作自定义标签的选项,您可以指定列表或设置排列。有关文档,请参见此处:https ://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.xticks.html

这是我为反映一些实验结果而编写的代码示例:

x = np.arange(1,6, dtype=int)
ynt = np.array([97.16666667,97.83333333,96.83333333,97.5,98.83333333]) # Valores de la muestra as received
eant = np.array([1.178511302,1.247219129,0.849836586,0.971825316,1.545603083])

yv10 = np.array([113.3333333,124.6666667,126,121,115.6666667]) # Valores IF @v10 (M4)
ev10 = np.array([2.309401077,5.507570547,5.567764363,3.464101615,5.131601439])

yv5 = np.array([110.6666667,117.6666667,113.3333333,112,120.3333333]) # Valores IF @v5 (M5)
ev5 = np.array([2.081665999,2.886751346,3.785938897,7,9.018499506])

fig = plt.figure(1)
plt.xticks(x, fontsize = 12)
plt.yticks(fontsize = 12)
plt.ylabel(r'Hardness (HV)', fontsize= 12)
plt.xlabel('Depth', fontsize= 12)

plt.plot(x, ynt, color='gray', label = 'non-treated')
plt.errorbar(x, ynt, eant,color = 'gray' ,linestyle='None', marker='^')

plt.plot(x, yv10, color='#125fe3', label = '10 mm/s')
plt.errorbar(x, yv10, eant,color = '#125fe3' ,linestyle='None', marker='^')

plt.plot(x, yv5, color='#e09214', label = '5 mm/s')
plt.errorbar(x, yv5, eant,color = '#e09214' ,linestyle='None', marker='^')

plt.title('Average Microhardness\nIF steel')
# plt.xlabel(r'Depth')

例子


推荐阅读