要实现您想要的操作--将每个条形图设置在x轴上的特定位置,您需要 for each 条形图使用set_x()
.你可以用container.get_children()
得到它,然后移动它.
请注意,我将数据作为数据帧,并添加了一个名为pos
的列.这将定义每个条形距x轴零的距离.绘制条形图,然后使用set_x()移动条形图,使用plt.xlim()
和plt.xticks()
对齐刻度和标签.希望这就是你要找的.
# creating the dataset - Using dataframe and adding pos column for distance from zero
data = {'courses' : ['C', 'C++', 'Java', 'Python'], 'values' : [20, 15, 30, 35], 'pos' : [2, 3, 5, 7]}
df=pd.DataFrame(data)
fig = plt.figure(figsize = (10, 5))
# creating the bar plot
plt.bar(df['courses'], df['values'], color ='maroon', width = 0.4)
plt.xlabel("Courses offered")
plt.ylabel("No. of students enrolled")
plt.title("Students enrolled in different courses")
## Set xlim from 0 to largest value plus 0.5 to show all bars
plt.xlim(0, df.pos.max()+0.5)
## Access each bar and set the position based on value in df.pos
for container in plt.gca().containers:
for i, child in enumerate(container.get_children()):
child.set_x(df.pos[i]-0.2) ## 0.2 as you set width=0.4
##Adjust ticks and ticklabels
plt.xticks(ticks=df.pos, labels=df.courses)
plt.show()