首页 > 解决方案 > matplotlib python中带有三个y轴的三个条形图

问题描述

我想在 matplotlib python 中使用三个带有三个 y 轴的条形图。

我使用两个带两个 y 轴的条形图,一切正常 在此处输入图像描述,

但是一旦添加了第三个就不好了。 在此处输入图像描述

我想用黑色添加第三个比例。

请您的帮助。

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')

标签: pythonmatplotlibbar-chartaxes

解决方案


从您的链接中,它现在解决了,因为

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()

再次感谢。


推荐阅读