Reputation: 482
I want y-ticks on both sides(left & right), but with different labels at the same y points. I tried following, but I'm not able to position ticks at same location.
I'm newbie to matplotlib. I have gone through the matplotlib example, but couldn't figure it out the solution to my problem.
http://matplotlib.org/examples/pylab_examples/barchart_demo2.html
Greatly appreciate any suggestions.
Here is the code:
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()
Upvotes: 2
Views: 3279
Reputation: 87566
I think you got caught by a bit of trickery in that example. There is a plot([100, 100], [0, 5])
in the demo code which is doing a lot of non-obvious work (I am working on submitting a PR to improve the demo) in making sure that the ylimits are the same for both yaxis
.
You just need to add a
ax2.set_ylim(ax.get_ylim())
before you call show
.
You also have an un-related error ax2.set_yticklabels(group_cnt)
-> ax2.set_yticklabels(groups)
.
[side note, generated PR #2327]
Upvotes: 1