栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Matplotlib绘图——柱状图(一列,多列)并在柱子上显示数值

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Matplotlib绘图——柱状图(一列,多列)并在柱子上显示数值

文章目录
  • 1、导入包
  • 2、一列柱状图
  • 3、多列柱状图

1、导入包
import warnings
warnings.filterwarnings('ignore') 

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rcParams

# 设置全局字体及大小,设置公式字体
config = {
    "font.family":'serif',        # 衬线字体
    "font.size": 12,              # 相当于小四大小
    "mathtext.fontset":'stix',    # matplotlib渲染数学字体时使用的字体,和Times New Roman差别不大
    "font.serif": ['SimSun'],     # 宋体SimSun
    "axes.unicode_minus": False,  # 用来正常显示负号
    "xtick.direction":'in',       # 横坐标轴的刻度设置向内(in)或向外(out)
    "ytick.direction":'in',       # 纵坐标轴的刻度设置向内(in)或向外(out)
}
rcParams.update(config)

%matplotlib inline 
# 内置魔法函数,不用再 plt.show()
2、一列柱状图
#定义函数来显示柱子上的数值
def autolabel(rects):
    for rect in rects:
        height = rect.get_height()
        plt.text(rect.get_x()+rect.get_width()/2.-0.08, 1.03*height, '%s' % int(height), size=10, family="Times new roman")

plt.figure(figsize=(4,3))

x = ["A", "B", "C", "D"]
y = [ 65,  70,  75,  80]

cm = plt.bar(x, y, width=0.5, color=["blue", "green", "yellow", "magenta"])
autolabel(cm)

plt.ylim((0, 90))
plt.xlabel("类别", size=12)
plt.ylabel("数量", size=12)
plt.xticks(fontproperties='Times New Roman', size = 10)
plt.yticks(fontproperties='Times New Roman', size = 10)

plt.savefig(r'D:UsersAdministratorDesktop一列柱状图.png', dpi=600, bbox_inches='tight')
plt.show()

3、多列柱状图
labels = ["A", "B", "C", "D", "E"]
X =      [ 60,  65,  70,  75,  80]
Y =      [ 65,  70,  75,  80,  85]
Z =      [ 70,  75,  80,  85,  90]

barWidth = 0.25   # 设置柱子的宽度
# 设置横轴刻度在多列柱子的中间
r1 = np.arange(len(X))
r2 = [x + barWidth for x in r1]
r3 = [x + barWidth for x in r2]

#定义函数来显示柱子上的数值
def autolabel(rects):
    for rect in rects:
        height = rect.get_height()
        plt.text(rect.get_x()+rect.get_width()/2.-0.08, 1.02*height, '%s' % int(height), size=10, family="Times new roman")

plt.figure(figsize=(6,4))
cm = plt.bar(r1, X, color='cyan',    width=barWidth, edgecolor='white', label='X')
autolabel(cm)
cm = plt.bar(r2, Y, color='yellow',  width=barWidth, edgecolor='white', label='Y')
autolabel(cm)
cm = plt.bar(r3, Z, color='magenta', width=barWidth, edgecolor='white', label='Z')
autolabel(cm)

plt.ylim((0, 100))
plt.xlabel("类别", size=12)
plt.ylabel("数量", size=12)
plt.yticks(fontproperties='Times New Roman', size=10)
plt.xticks([r + barWidth for r in range(len(X))], labels=labels, fontproperties='Times New Roman', size=10)
plt.legend(prop={'family': 'Times New Roman', 'size': 10})

plt.savefig(r'D:UsersAdministratorDesktop多列柱状图.png', dpi=600, bbox_inches='tight')
plt.show()

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/926132.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号