使用matplotlib为水平条形图创建备用y轴标签

问题描述 投票:2回答:2

这是我刚刚提出的问题的一个(更清楚的)转发,我的认证让人很困惑。

嗨,我是新手使用matplotlib.pyplot在python中绘图并花了很多时间在这个网站和其他人上搜索,并试图解决这个问题,但我还没有成功完成我想做的事情。

使用下面的代码,我生成了以下图表,该图表是一系列课程和已完成课程的学生的百分比:我的代码创建的内容:

但是,我想用python生成的内容类似于以下内容(粗略地用MS绘制,以便向您传达我想要生成的代码):

我想要创建的内容:

右侧轴标签是每个课程注册的人数,这是我想要的其他信息。另一种解决方案是在图表中显示注册号,写在栏末尾。但无论做什么都可以。

import matplotlib.pyplot as plt
y = ['Physics','Chemistry','Economics','Philosophy','Computer Science','Sociology','Biology','History','Overall']
x = [0.0,33.333333333333336,50.0,50.0,50.0,54.54545454545455,58.333333333333336,100.0,51.851851851851855]
alternativeYlabels = ['54', '1', '3', '12', '12', '2', '11', '12', '1']
plt.barh(y,x)
plt.title('Percent Completion Rate of Each Course')

plt.show()

如何更改我的代码以满足我的需求?另外,我如何在我的情节中添加对应于每个20%的垂直网格线?

谢谢

python matplotlib
2个回答
0
投票

以下是两种解决方案:您需要添加twinx轴。在plt.show()之前添加以下行。如果你想把值放在右边的条形而不是第二个y轴上,你可以看一下我几周前提供的this类似的答案(我附上下面的代码以及输出)。

ax.xaxis.grid(True) # adding vertical grid lines
ax2 = ax.twinx() # Creating the right hand side y axis
ax_lim = ax.get_ylim()
ax2_lim = (ax_lim[0], ax_lim[1]) # Aligning the limits of both y axes
ax2.set_ylim(ax2_lim)
ax2.set_yticks(range(0, len(y)))
ax2.set_yticklabels(alternativeYlabels[::-1]) # Reverses the list
ax2.set_ylabel("# enrolled in each course",rotation = 270, labelpad=15)

产量

enter image description here

替代所需输出(请参阅答案中的链接)编辑:基于@RentancenOfBeingErnest建议的文本垂直对齐

ax.xaxis.grid(True)
for i in range(len(x)):
    ax.text(x[i]+1, i, alternativeYlabels[::-1][i], color='black', fontweight='bold', va="center")

产量

enter image description here


0
投票

我修改了this matplotlib示例中的代码,该示例在绘图的两侧都有两个单独的刻度。主要区别在于,第二个条形图是虚拟条形图(每个条形图的高度为0)。我认为这是最简单的方法(无需手动添加刻度等)

# Initialize parameters as in your post
import matplotlib.pyplot as plt
y = ['Physics','Chemistry','Economics','Philosophy','Computer Science','Sociology','Biology','History','Overall']
x = [0.0,33.333333333333336,50.0,50.0,50.0,54.54545454545455,58.333333333333336,100.0,51.851851851851855]
alternativeYlabels = ['54', '1', '3', '12', '12', '2', '11', '12', '1']

# This time draw the bar plot from an 'axes' object
ax1 = plt.subplot(111)
ax1.barh(y,x)

# Draw a second 'dummy' barplot just to define the second ticks
ax2 = ax1.twinx()
ax2.barh(range(len(x)), [0]*len(x), tick_label=alternativeYlabels[::-1])  # don't forget to reverse the labels 

# Add the vertical grid
ax1.xaxis.grid(True)

# Add a title and show figure
plt.title('Percent Completion Rate of Each Course')
plt.show()

运行下面的代码应该产生这个数字:

© www.soinside.com 2019 - 2024. All rights reserved.