python实现垂直柱状图与折线图组合图

目录

一、直接上代码

二、运行结果展示


一、直接上代码

#导入库
import pandas as pd
import matplotlib.pyplot as plt

#自定义函数
def plot_combination():
    sale = pd.read_excel('./数据/城乡收支情况.xlsx', header=0, index_col=0)
    # 设置正常显示中文标签
    plt.rcParams['font.sans-serif'] = ['SimHei']
    # 正常显示负号
    plt.rcParams['axes.unicode_minus'] = False
    # 设置字体大小
    plt.rcParams.update({'font.size': 16})

    # 提取数据
    x = sale['年份']
    y1 = sale['城镇可支配收入(元)']
    y2 = sale['农村居民可支配收入(元)']
    y3= sale['城乡居民的收入之比/%']

    plt.figure(figsize=(16, 8))
    plt.subplot(111)



    # 柱形宽度
    bar_width = 0.35

    # 在主坐标轴绘制柱形图
    # plt.bar(x, y1, bar_width,color='r', label='城镇可支配收入(元)')
    # plt.bar(x + bar_width, y2, bar_width,color='#FFFF00', label='农村居民可支配收入(元)')
    plt.bar(x, y1, bar_width,color='k', label='城镇可支配收入(元)')
    plt.bar(x + bar_width, y2, bar_width,color='#00ff00', label='农村居民可支配收入(元)')

    # 设置坐标轴的取值范围,避免柱子过高而与图例重叠
    plt.ylim(0, max(y1.max(), y2.max()) * 1.2)

    # 设置图例
    plt.legend(loc='upper left')
    plt.ylabel("单位:元",fontsize=20, loc="center")

    # 设置横坐标的标签
    plt.xticks(x)
    #plt.set_xticklabels(sale.index)
    plt.xlabel("年份",fontsize=20, loc="center")

    # 在次坐标轴上绘制折线图
    plt.twinx()
    # ls:线的类型,lw:宽度,o:在顶点处实心圈
    plt.plot(x, y3, ls='--', lw=2, color='c', marker='*',ms = 20, mfc = 'm', label='城乡居民收入占比')

    # 设置次坐标轴的取值范围,避免折线图波动过大
    plt.ylim(2, 3)

    # 设置图例
    plt.legend(loc='best')

    # 定义显示百分号的函数
    def to_percent(number, position=0):
        return '%.f' % (number) + '%'

    # 次坐标轴的标签显示百分号 FuncFormatter:自定义格式函数包
    from matplotlib.ticker import FuncFormatter
    plt.gca().yaxis.set_major_formatter(FuncFormatter(to_percent))

    # 设置标题
    plt.title('\n2015年-2021年城乡居民可支配收入及城乡之间的占比\n', fontsize=26, loc='center', color='k')

    plt.ylabel("单位%:",fontsize=20, loc="center")

    plt.savefig('./figure.jpg', bbox_inches='tight')

    plt.show()

if __name__ == '__main__':

    plot_combination()

二、运行结果展示

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

青枫浦上看桃花

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值