Search code examples
pythonmatplotlibplotdata-visualizationvisualization

matplotlib multiple groups with different scale


I have the following script but the resulting plot for the second group is skewed by the first one.

labels = ['CA',  'ME']
Addmitted = [500000, 100]
Applied = [10000000, 1000]

x = np.arange(len(labels))  
width = 0.35  

fig, ax = plt.subplots()
rects1 = ax.bar(x - width/2, Addmitted, width, label='Admitted')
rects2 = ax.bar(x + width/2, Applied, width, label='Applied')

ax.set_xticks(x, labels)
ax.legend()

ax.bar_label(rects1, padding=3)
ax.bar_label(rects2, padding=3)

fig.tight_layout()
plt.ylim(0, 12000000)

plt.show()

enter image description here


Solution

  • I am posting as an answer but there is probably a better way to do this:

    labels = ['CA',  'ME']
    Addmitted_l = [500000, 0]
    Applied_l = [10000000, 0]
    
    Addmitted_r = [0, 120]
    Applied_r = [0, 300]
    
    x = np.arange(len(labels))  
    width = 0.2  
    
    fig, ax = plt.subplots()
    rects1 = ax.bar(x - width/2, Addmitted_l, width, label='Admitted')
    rects2 = ax.bar(x + width/2, Applied_l, width, label='Applied')
    
    ax2 = ax.twinx()
    rects3 = ax2.bar(x - width/2, Addmitted_r, width, label='Admitted')
    rects4 = ax2.bar(x + width/2, Applied_r, width, label='Applied')
    
    ax.set_xticks(x, labels)
    ax2.legend(loc='upper center')
    
    ax.ticklabel_format(style='plain', axis='y')
    fig.tight_layout()
    
    plt.show()
    

    enter image description here