Different y-scales for barplot with multiple groups

Question:

I have two groups in a barplot in `matplotlib` with measurements on different scales. I want the one on the right to have a separate y axis to not appear shrinked with respect to the one on the left. This is what I’ve tried so far:

CODE:

``````import numpy as np
import matplotlib.pyplot as plt

plt.rcParams['figure.dpi'] = 300
plt.rcParams['font.size'] = 14

# set width of bars
barWidth = 0.15

bars1   = [10, 0.5]
bars2   = [11, 0.8]
bars3   = [20, 1.0]
bars4   = [30, 1.5]
bars5   = [40, 1.8]

# Set position of bar on X axis
r1 = np.arange(len(bars1))
r2 = [x + barWidth for x in r1]
r3 = [x + barWidth for x in r2]
r4 = [x + barWidth for x in r3]
r5 = [x + barWidth for x in r4]

# Make the plot
fig, ax = plt.subplots(figsize=(8, 6))
ax.bar(r1, bars1, color='#7f6d5f', width=barWidth, edgecolor='white')
ax.bar(r2, bars2, color='#557f2d', width=barWidth, edgecolor='white')
ax.bar(r3, bars3, color='#2d7f5e', width=barWidth, edgecolor='white')
ax.bar(r4, bars4, color='#2d7f5e', width=barWidth, edgecolor='white')
ax.bar(r5, bars5, color='#2d7f5e', width=barWidth, edgecolor='white')

# Create secondary y-axis for the right group
ax2 = ax.twinx()

group_labels = ['group1', 'group2']
ax.set_xticks([r + 2 * barWidth for r in range(len(bars1))])
ax.set_xticklabels(group_labels)

ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
plt.show()
``````

Current output:

how can I make `group2` be affected only by `scale2`?

You need to call `ax2.bar` for the elements of `group2`, something like this:

``````# Make the plot
fig, ax = plt.subplots(figsize=(8, 6))
ax2 = ax.twinx()

for r, bar, color in zip([r1, r2, r3, r4, r5],
[bars1, bars2, bars3, bars4, bars5],
['#7f6d5f', '#557f2d'] + ['#2d7f5e'] * 3):
kwargs = {'color': color,
'width': barWidth,
'edgecolor': 'white'}
ax.bar(r[0], bar[0], **kwargs)
ax2.bar(r[1], bar[1], **kwargs)
``````

Output:

Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.