如何在相同的刻度位置获得两侧的刻度

时间:2013-08-22 00:26:27

标签: matplotlib

我想在两侧(左侧和右侧)使用y-ticks,但在相同的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()

1 个答案:

答案 0 :(得分:1)

我认为你在这个例子中被一点诡计所困扰。演示代码中有一个plot([100, 100], [0, 5])正在做很多非显而易见的工作(我正在提交PR以改进演示),以确保{{1}的ylimits相同}。

你只需要添加一个

yaxis
在致电ax2.set_ylim(ax.get_ylim()) 之前

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

[旁注,生成PR #2327]