Python:matplotlib绘制柱状图Bar

Python:matplotlib绘制柱状图Bar

import numpy as np
import matplotlib.pyplot as plt


def get_data():
    size = 5
    border = 80
    x = np.linspace(start=1, stop=size, endpoint=True, num=size, dtype=np.int)
    # x = np.arange(start=1, stop=size+1, step=1, dtype=np.int)
    y1 = np.random.randint(low=border, high=100, size=size)
    y2 = np.random.randint(low=50, high=border, size=size)
    ret = (x, y1, y2)
    return ret


def main():
    plt.rcParams['font.sans-serif'] = ['SimHei']  # 中文乱码
    plt.rcParams['axes.unicode_minus'] = False  # 正负号

    data = get_data()

    plt.figure(figsize=(15, 10))
    plt.bar(x=data[0], height=data[1], alpha=0.5, width=0.6, color='green', edgecolor='red', label='直方图1', lw=3)
    plt.bar(x=data[0], height=data[2], alpha=0.8, width=0.4, color='blue', edgecolor='yellow', label='直方图2', lw=3)

    # 图例位置
    plt.legend(loc='upper center')

    plt.xlabel('x坐标轴', fontsize=25)
    plt.ylabel('y坐标轴', fontsize=20)
    plt.title('直方图(柱状图)', fontsize=30)

    # 若设置将覆盖默认的坐标轴刻度值。
    # 默认的刻度值即是x=data[0]
    plt.xticks(ticks=np.arange(start=1, stop=6, step=1), labels=list('zhang'), rotation=45, size=30, color='red')

    # 若设置将覆盖默认的坐标轴刻度值。
    # 默认的刻度值即是y=data[1],y=data[2]
    # 默认的刻度值由系统自动生成。
    plt.yticks(ticks=np.linspace(start=30, stop=120, endpoint=True, num=10, dtype=np.int), rotation=90)

    # 画网格
    plt.grid(axis='x', linestyle='--', linewidth=3, color='red')  # 显示竖直的网格线
    plt.grid(axis='y', linestyle='-.', linewidth=3, color='gray')  # 显示水平的网格线

    axs = plt.axes()

    # 顶部和右部的边框线消失
    axs.spines['top'].set_visible(False)
    axs.spines['right'].set_visible(False)
    axs.spines['left'].set_color('red')
    axs.spines['left'].set_linewidth(5)
    axs.spines['bottom'].set_linewidth(10)

    # 取消(消失)所有的框线,刻度,label,只保留纯粹的柱状bar
    # plt.axis('off')
    plt.show()


if __name__ == '__main__':
    main()

 

输出结果如图:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

zhangphil

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

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

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

打赏作者

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

抵扣说明:

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

余额充值