python 绘图 —— 绘制从顶部向底部显示的柱形图[ax.bar()]

python 绘图 —— 绘制从顶部向底部显示的柱形图[ax.bar()]

效果图如下所示:
在这里插入图片描述
就是这个样子,一般比较少见将柱形图从上往下绘制的。可能是会为了更好的展示数据对比结果吧。这里绘图的主要思路如下:

  • 利用ax.twinx()这个函数生成一个新的x轴(相当于复制了一个x轴)
  • 使用ax.invert_yaxis()这个函数反转新x轴对应的y轴,使其从图中左边0-100排列变成100-0排列,这样就保证了图片从顶往底显示的效果
  • 手动设置新的y轴的ticklabel,使其展现为0-100排列。

具体步骤如下所示:

1、首先是生成随机一组数据并绘制柱形图:


import numpy as np
import matplotlib.ticker as mticker
import matplotlib.pyplot as plt
###########################################################################
plt.rcParams['font.sans-serif']=['SimHei']#中文 
plt.rcParams['axes.unicode_minus']=False  #显示负号
# ####################################data#################################
n=6
y  = np.linspace(10,70,n)
y1 = np.linspace(10,60,n)
y2 = np.linspace(10,50,n)
x=np.linspace(2000,2020,n)

data = np.array([y,y1,y2])
width = 0.6
# ####################################draw#################################
fig=plt.figure(figsize=(5,7),dpi=500)#添加画布等
ax=fig.add_axes([0,0,1,0.3])
ax.set(xlim=(2000,2021),ylim=(0,100)) 
bar1=ax.bar(x - width,data[0],
            # color=np.where(y>0,'r','b'), #判断大于0的为红色,负的为蓝色
            width=0.5,   #柱形宽度
            align='center', #柱形的位置edge/center 
            alpha=0.8,    #柱形透明度
            hatch='*',    #柱形表明的形状样式
            edgecolor='k',#柱形边缘颜色
            bottom=0.01   #柱形离底部的距离
          )
bar2=ax.bar(x + width,data[1],
            # color=np.where(y>0,'r','b'), #判断大于0的为红色,负的为蓝色
            width=0.5,   #柱形宽度
            align='center', #柱形的位置edge/center 
            alpha=0.8,    #柱形透明度
            hatch='*',    #柱形表明的形状样式
            edgecolor='k',#柱形边缘颜色
            bottom=0.01   #柱形离底部的距离
          )
bar3=ax.bar(x ,data[2],
            # color=np.where(y>0,'r','b'), #判断大于0的为红色,负的为蓝色
            width=0.5,   #柱形宽度
            align='center', #柱形的位置edge/center 
            alpha=0.8,    #柱形透明度
            hatch='*',    #柱形表明的形状样式
            edgecolor='k',#柱形边缘颜色
            bottom=0.01   #柱形离底部的距离
          )
##########################################################################
ax.set(xlim=(1999,2021),ylim=(0,100))   #设置x、y轴的最大最小范围
ax.set_xticks(np.linspace(2000, 2020, n)) #设置x轴显示的标签         #添加注释
ax.axhline(y=0,c='k',ls=':',lw=1)    #添加水平线,设置颜色,位置,水平线的style
#设置轴的参数,间隔
ax.tick_params(axis='both',which='both',direction='in')
ax.yaxis.set_minor_locator(mticker.MultipleLocator(5))
ax.xaxis.set_minor_locator(mticker.MultipleLocator(5))
# 设置label
ax.set_xlabel('年份 (Year)')
ax.set_ylabel('数值 (%) ')
ax.set_title('柱状图',fontsize=10)

在这里插入图片描述

2、复制一个新的x轴,并生成一组数据绘制柱形图

ax2 = ax.twinx()
ax2.set(xlim=(1999,2021),ylim=(100)) 
bar4 = ax2.bar(x,np.linspace(4,6,n),
        width=0.5,   #柱形宽度
        align='center', #柱形的位置edge/center 
        alpha=0.8,    #柱形透明度
        hatch='*',    #柱形表明的形状样式
        edgecolor='k',#柱形边缘颜色
        bottom=0.01  , #柱形离底部的距离
        color='r'
        )
ax2.yaxis.set_minor_locator(mticker.MultipleLocator(5))

在这里插入图片描述

3、翻转y轴,稍微调整一下tick的方向

ax2.invert_yaxis()
ax2.tick_params(axis='both',tickdir='in')
ax2.tick_params(which='minor',tickdir='in')

在这里插入图片描述

4、 重新定义ticklabel的值

ax2.set_yticklabels(['0','20','40','60','80','100'][::-1])

在这里插入图片描述

以下是全部的代码:

# -*- coding: utf-8 -*-
"""
Created on Tue Feb 21 14:49:36 2023

@author: jianpu

@blog :  https://blog.csdn.net/weixin_44237337?spm=1000.2115.3001.5343

@email: 211311040008@hhu.edu.cn

introduction : keep learning althongh walk slowly
"""


import numpy as np
import matplotlib.ticker as mticker
import matplotlib.pyplot as plt
###########################################################################
plt.rcParams['font.sans-serif']=['SimHei']#中文 
plt.rcParams['axes.unicode_minus']=False  #显示负号
# ####################################data#################################
n=6
y  = np.linspace(10,70,n)
y1 = np.linspace(10,60,n)
y2 = np.linspace(10,50,n)
x=np.linspace(2000,2020,n)

data = np.array([y,y1,y2])
width = 0.6
# ####################################draw#################################
fig=plt.figure(figsize=(5,7),dpi=500)#添加画布等
ax=fig.add_axes([0,0,1,0.3])
ax.set(xlim=(2000,2021),ylim=(0,100)) 
bar1=ax.bar(x - width,data[0],
            # color=np.where(y>0,'r','b'), #判断大于0的为红色,负的为蓝色
            width=0.5,   #柱形宽度
            align='center', #柱形的位置edge/center 
            alpha=0.8,    #柱形透明度
            hatch='*',    #柱形表明的形状样式
            edgecolor='k',#柱形边缘颜色
            bottom=0.01   #柱形离底部的距离
          )
bar2=ax.bar(x + width,data[1],
            # color=np.where(y>0,'r','b'), #判断大于0的为红色,负的为蓝色
            width=0.5,   #柱形宽度
            align='center', #柱形的位置edge/center 
            alpha=0.8,    #柱形透明度
            hatch='*',    #柱形表明的形状样式
            edgecolor='k',#柱形边缘颜色
            bottom=0.01   #柱形离底部的距离
          )
bar3=ax.bar(x ,data[2],
            # color=np.where(y>0,'r','b'), #判断大于0的为红色,负的为蓝色
            width=0.5,   #柱形宽度
            align='center', #柱形的位置edge/center 
            alpha=0.8,    #柱形透明度
            hatch='*',    #柱形表明的形状样式
            edgecolor='k',#柱形边缘颜色
            bottom=0.01   #柱形离底部的距离
          )
##########################################################################
ax.set(xlim=(1999,2021),ylim=(0,100))   #设置x、y轴的最大最小范围
ax.set_xticks(np.linspace(2000, 2020, n)) #设置x轴显示的标签         #添加注释
ax.axhline(y=0,c='k',ls=':',lw=1)    #添加水平线,设置颜色,位置,水平线的style
#设置轴的参数,间隔
ax.tick_params(axis='both',which='both',direction='in')
ax.yaxis.set_minor_locator(mticker.MultipleLocator(5))
ax.xaxis.set_minor_locator(mticker.MultipleLocator(5))
# 设置label
ax.set_xlabel('年份 (Year)')
ax.set_ylabel('数值 (%) ')
ax.set_title('柱状图',fontsize=10)
  #添加图例
ax2 = ax.twinx()
ax2.invert_yaxis()
ax2.set(xlim=(1999,2021),ylim=(100)) 
ax2.set_yticklabels(['0','20','40','60','80','100'][::-1])
bar4 = ax2.bar(x,np.linspace(4,6,n),
        width=0.5,   #柱形宽度
        align='center', #柱形的位置edge/center 
        alpha=0.8,    #柱形透明度
        hatch='*',    #柱形表明的形状样式
        edgecolor='k',#柱形边缘颜色
        bottom=0.01  , #柱形离底部的距离
        color='r'
        )
ax2.yaxis.set_minor_locator(mticker.MultipleLocator(5))
ax2.tick_params(axis='both',tickdir='in')
ax2.tick_params(which='minor',tickdir='in')
ax.legend([bar1,bar2,bar3,bar4],['柱形1','柱形2','柱形3','柱形4'])
plt.show()

具体代码是按照之前的一个教程修改的:绘制正负区分的柱形图[ax.bar()]

				欢迎评论或者加我交流,分享更简单的绘制方法~
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

简朴-ocean

继续进步

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

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

打赏作者

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

抵扣说明:

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

余额充值