Search code examples
pythonmatplotlibbar-chartaxes

Three bars with three y-axes in matplotlib python


I'd like to use three bars with three y-axes in matplotlib python.

I use two bars with two y-axes, everything is ok Ref. enter image description here,

but once added the third one is not good. enter image description here

I'd like to add the third scale using black color.

Please your help.

width = 0.25
fig, ax1 = plt.subplots()
ind = np.arange(len(r2_score1))
print 'r2_score1', r2_score1
rects1 = ax1.bar(ind, r2_score1, width, color = 'b')
ax1.set_xticks(ind+width)
ax1.set_xticklabels(names, fontsize=14)
ax1.set_ylabel('r2_score', color='b')
for tl in ax1.get_yticklabels():
    tl.set_color('b')


ax2 = ax1.twinx()
rects2 = ax2.bar(ind + width, time_model, width, color = 'r')
ax2.set_ylabel('Time (s)', color='r')
for tl in ax2.get_yticklabels():
   tl.set_color('r')


ax3 = ax2.twinx()
rects3 = ax3.bar(ind + width+ width, rmse, width, color = 'k')
ax3.set_ylabel('rmse', color='k')
for tl in ax3.get_yticklabels():
   tl.set_color('k')

Solution

  • From your links, it solved it now, as

    width = 0.25
    from mpl_toolkits.axes_grid1 import host_subplot
    from mpl_toolkits import axisartist
    host = host_subplot(111, axes_class=axisartist.Axes)
    plt.subplots_adjust(right=0.75)
    
    par1 = host.twinx()
    par2 = host.twinx()
    
    par2.axis["right"] = par2.new_fixed_axis(loc="right", offset=(80, 0))
    
    par1.axis["right"].toggle(all=True)
    par2.axis["right"].toggle(all=True)
    
    ind = np.arange(len(r2_score1))
    print 'r2_score1', r2_score1
    rects1 = host.bar(ind, r2_score1, width, color = 'b')
    host.set_xticks(ind+width)
    host.set_xticklabels(names, fontsize=20)
    for tl in host.get_yticklabels():
        tl.set_color('b')
    
    
    print 'time_model', time_model
    rects2 = par1.bar(ind + width, rmse, width, color = 'k')
    for tl in par1.get_yticklabels():
       tl.set_color('k')
    
    
    
    
    rects3 = par2.bar(ind + width+ width,  time_model, width, color = 'r')
    for tl in par2.get_yticklabels():
       tl.set_color('r')
    
    host.set_xticklabels(names, fontsize=20)
    host.set_ylabel('$R^2$ Score',  color='b')
    par1.set_ylabel('RMSE',  color='k')
    par2.set_ylabel('Time (ms)',  color='r')
    
    
    host.legend()
    plt.show()
    

    Thanks again.