python-绘制双轴柱状图

29 篇文章 2 订阅

转载:https://blog.csdn.net/weixin_42749944/article/details/115026810

df = pd.read_excel(r'./file.xlsx')

fig, ax1 = plt.subplots()
width = 0.4
x1_list = []
x2_list = []

for i in range(len(df)):
    x1_list.append(i)
    x2_list.append(i + width)

b1 = ax1.bar(x1_list, df['a'],width=width,label='a',color = sns.xkcd_rgb["pale red"],tick_label = df.index)

ax2 = ax1.twinx()
b2 = ax2.bar(x2_list, df['b'],width=width,label='b',color = sns.xkcd_rgb["denim blue"],tick_label = df.index)

#ax1.set_title('',fontsize = 14)
ax1.set_xlabel('1',fontsize=12)
ax1.set_ylabel('a(m)',fontsize=12)
ax2.set_ylabel('b($km^{3}$)',fontsize=12)

#ax1.set_xticklabels(ax1.get_xticklabels(),rotation = 25)
ax1.set_xticklabels(['2010','2011','2012','2013','2014','2015','2016','2017','2018','2019','2020'],fontsize = 10)

ax1.yaxis.label.set_color(b1[0].get_facecolor())
ax2.yaxis.label.set_color(b2[0].get_facecolor())

ax1.tick_params(axis = 'y', colors = b1[0].get_facecolor())
ax2.tick_params(axis = 'y', colors = b2[0].get_facecolor())

plt.axhline(y=0, ls='--', c='k')

plt.legend(handles = [b1,b2])

# plt.savefig('fig.png', dpi=200,bbox_inches = 'tight')

plt.show()

双轴零点不在同一条水平线上:
在这里插入图片描述
但是我想要双轴起点相同,调整Y轴取值范围:

ax2.set_ylim(1, 2)

在这里插入图片描述
关于颜色设置:seaborn.xkcd_palette
https://xkcd.com/color/rgb/
在这里插入图片描述

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值