2

我想要两边(左和右)的 y 刻度,但在相同的 y 点上有不同的标签。我尝试了以下操作,但无法将刻度定位在同一位置。

我是 matplotlib 的新手。我已经浏览了 matplotlib 示例,但无法解决我的问题。

http://matplotlib.org/examples/pylab_examples/barchart_demo2.html

非常感谢任何建议。

这是代码:

import numpy as np
import matplotlib.pyplot as plt

groups = [ 1, 2, 3, 4, 5 ]
members = [ 1, 2, 3, 4 ]
colors = [ 'r', 'y', 'b', 'k']


#store score of members for the groups
scores = {member: 100*np.random.rand(len(groups)) for member in members}

group_cnt = group_cnt = sum([scores[member] for member in members])
print scores

fig = plt.figure(figsize=(8,6))
ax = fig.add_subplot(111)

width_bar = 0.5
width_space = 0.2

#position of barh
total_space = len(groups)*(len(members)*width_bar)+(len(groups)-1)*width_space
ind_space = len(members)*width_bar
step = ind_space/2.
#pos for labels
pos = np.arange(step, total_space+width_space, ind_space+width_space)
#pos for grin lines
minor_pos = np.arange(ind_space, total_space+width_space, ind_space+width_space)


for idx in xrange(len(members)):
    ax.barh(pos-step+idx*width_bar, scores[members[idx]], width_bar, edgecolor='k', color=colors[idx], linewidth=3)

ax.invert_yaxis()
ax.set_yticks(pos)
ax.set_yticklabels(groups) 

ax.set_yticks(minor_pos, minor=True)
ax.grid(True, which='minor')
ax.set_ylabel('Groups')

ax2 = ax.twinx()
ax2.set_ylabel('Group totals')
ax2.set_yticks(pos)
ax2.set_yticklabels(group_cnt)
ax2.invert_yaxis()

plt.show()
4

1 回答 1

1

我认为你在那个例子中被一些诡计抓住了。演示代码中有一个plot([100, 100], [0, 5])正在做很多不明显的工作(我正在提交 PR 以改进演示)以确保两者的 ylimit 相同yaxis

你只需要添加一个

ax2.set_ylim(ax.get_ylim())

在你打电话之前show

您还有一个不相关的错误ax2.set_yticklabels(group_cnt)-> ax2.set_yticklabels(groups)

[旁注,生成PR #2327 ]

于 2013-08-22T03:59:34.200 回答