matplotlib 条形图中的偶数x刻度间距

brvekthn  于 2023-06-06  发布在  其他
关注(0)|答案(1)|浏览(455)

我正在尝试使用matplotlib使x均匀间隔。
这里是问题的情节;代码在x1c 0d1x下面

问题:尽管我已尽最大努力,但x轴条和值的间距并不均匀

我将感激任何和所有的帮助,谢谢!
这是我试图绘制的代码

# define and store student IDs
student_IDs = np.array([1453,1454,1456,1457,1459,1460,1462,1463,1464,1465,1466, 1467, 1468, 1469,1470])

before_IP_abs_scores = np.array([51,56,73,94,81,83,71,36,43,83,66,62,70,50,83])
after_IP_abs_scores = np.array([65,60,82,71,65,85,78,51,34,80,63,63,62,55,77])
change_IP_abs_scores = after_IP_abs_scores - before_IP_abs_scores

下面是我如何存储这个数组中的贵重物品

ip_sc = collections.OrderedDict()

for ii in student_IDs:
  ip_sc[ii]  = []
for count, key in enumerate(student_IDs):
  sci_id[key] = [before_science_ID_abs_scores[count],after_science_ID_abs_scores[count],change_science_ID_abs_scores[count]]
  ip_sc[key]  = [before_IP_abs_scores[count],after_IP_abs_scores[count],change_IP_abs_scores[count]]

下面是我的plotting代码:

fig = plt.figure(4)
fig.set_figheight(18)
fig.set_figwidth(18)

ax = plt.subplot(111)
plt.grid(True)
# ax = fig.add_axes([0,0,1,1])

for ii in student_IDs:
  # plt.plot([1,2], ip_sc[ii][:-1],label=r'${}$'.format(ii))
  ax.bar(ii, ip_sc[ii][0], width=.5, color='#30524F',edgecolor="white",hatch="//",align='center')
  ax.bar(ii, ip_sc[ii][1], width=.5, color='#95BC89',align='center')
  ax.bar(ii, ip_sc[ii][2], width=.5, color='#4D8178',align='center')
  
plt.ylabel('Absolute Score',size=30)
plt.xlabel('Student ID',size=30)
plt.title('IP Scale Scores',size=30)
plt.axhspan(0, 40, facecolor='navy', alpha=0.2,)
plt.axhspan(40, 60, facecolor='#95BC89', alpha=0.2)
plt.axhspan(60, 100, facecolor='seagreen', alpha=0.3)
ax.tick_params(axis='x', which='major', labelsize=16)
ax.tick_params(axis='y', which='major', labelsize=16)
plt.xticks(student_IDs, ['1453','1454','1456','1457','1459', '1460', '1462', '1463', '1464','1465', '1466', '1467', '1468', '1469', '1470'])
# ax.set_yticks(np.arange(0, 81, 10))
plt.ylim(-25,100)
ax.legend(labels=["Intense and Frequent IP ","Moderate IP ","few IP ",'Pre', 'Post','Change'],fontsize=15)
plt.show()
piv4azn7

piv4azn71#

student_id不是连续编号的。
您可以使用它们的索引作为x,而不是使用student_ids作为x值。使用set_xticklabels之后,您可以将student_ids设置为与这些位置对应的标签。
因此,您可以对代码进行以下修改(省略对plt.xticks的调用):

for ind, stud_id in enumerate(student_IDs):
    ax.bar(ind, ip_sc[stud_id][0], width=.5, color='#30524F', edgecolor="white", hatch="//", align='center')
    ax.bar(ind, ip_sc[stud_id][1], width=.5, color='#95BC89', align='center')
    ax.bar(ind, ip_sc[stud_id][2], width=.5, color='#4D8178', align='center')

ax.set_xticks(range(len(student_IDs)))
ax.set_xticklabels(student_IDs)

相关问题