用Matplotlib绘制横坐标为字符串型变量的柱状图

时间:2024-04-12 09:05:29

目的:废话不多说,本教程给出一个具体Demo,来实现利用Matplotlib来绘制一个横坐标为字符串型的柱状图

具体代码:

# -*- coding: utf-8 -*-
"""
Created on Sun May  5 10:19:20 2019

@author: Administrator
"""
  

#报道发布时间分布柱状图
import matplotlib.pyplot as plt
import matplotlib

from pylab import *
import numpy as np
# 设置中文字体和负号正常显示
plt.rcParams['font.sans-serif'] = ['SimHei']
matplotlib.rcParams['font.sans-serif'] = ['SimHei']
matplotlib.rcParams['axes.unicode_minus'] = False

label_list = ['2018.11','2018.12','2019.01','2019.02','2019.03','2019.04'] # 横坐标刻度显示值
num_list = [5,3,5,2,8,6] # 纵坐标刻度显示值
x = range(len(num_list))

"""
绘制条形图
left:长条形中点横坐标
height:长条形高度
width:长条形宽度,默认值0.8
label:为后面设置legend准备
"""

rects1 = plt.bar(left=x, height=num_list, width=0.4, alpha=0.8, color='red', label="Frequency statistics")
plt.ylim(0, 10)     # y轴取值范围
plt.ylabel("Frequency")

"""
设置x轴刻度显示值
参数一:中点坐标
参数二:显示值
"""

plt.xticks([index + 0.2 for index in x], label_list)
plt.xlabel("Month")
plt.title("")
plt.legend()     # 设置题注

# 编辑文本
for rect in rects1:
    height = rect.get_height()
    plt.text(rect.get_x() + rect.get_width() / 2, height, str(height), ha="center", va="bottom")

plt.show()

运行结果如图所示:

用Matplotlib绘制横坐标为字符串型变量的柱状图