0、环境
Python 3.8.9 Numpy matplotlib
感谢这个时代
1、公用导入头
import matplotlib.pyplot as plt
import numpy as np
plt.rc("font", family='Songti SC')
plt.rcParams['font.size'] = 8 # 字体大小
2、示例应用枚举
2.1 饼状图
代码:
# 1、饼状图
labels = "超市","网吧","医院","学校","超市2","网吧2","医院2","学校2","超市3","网吧3"
fracs = [5,10,15,17,3,18,2,7,8,15]
plt.axes(aspect=1) #使x y轴比例相同
explode = [0,0.05,0,0,0,0,0.1,0,0,0] # 突出某一部分区域
plt.pie(x=fracs, labels=labels, autopct='%.0f%%', explode=explode) #autopct显示百分比
plt.show()
2.2 折线图
代码:
squares = [1, 4, 9, 16, 25]
fig, ax = plt.subplots()
ax.plot(squares, linewidth=3)
#设置图表标题并给坐标轴加上标签。
ax.set_title("主题", size=14)
ax.set_xlabel("横坐标", size=14, color='red')
ax.set_ylabel("纵坐标", size=14, color='red')
ax.tick_params(axis='both', labelsize=14)
plt.show()
2.3 竖值条形图
代码:
N = 5
y = [20, 10, 30, 25, 15]
x = np.arange(N)
# 添加地名坐标
str1 = ("北京", "上海", "武汉", "深圳", "重庆")
# 绘图 x x轴, height 高度, 默认:color="blue", width=0.8
p1 = plt.bar(x, height=y, width=0.5, label="城市指标", tick_label=str1)
# 添加数据标签
for a, b in zip(x, y):
plt.text(a, b + 0.05, '%.0f' % b, ha='center', va='bottom', fontsize=10)
# 添加图例
plt.legend()
# 展示图形
plt.show()
2.4 叠加型条形图
代码:
x = np.arange(4)
Bj = [52, 55, 63, 53]
Sh = [44, 66, 55, 41]
str1 = ("北京", "上海", "武汉", "深圳")
bar_width = 0.3
# 绘图
plt.bar(x, Bj, bar_width)
plt.bar(x, Sh, bar_width, bottom=Bj,tick_label=str1)
# 展示图片
plt.show()
2.5 双属性条形图
代码:
x = np.arange(4)
Bj = [52, 55, 63, 53]
Sh = [44, 66, 55, 41]
str1 = ("北京", "上海", "武汉", "深圳")
bar_width = 0.3
# 设置x,y轴标签
plt.xlabel("测试难度")
plt.ylabel("试卷份数")
plt.bar(x, Bj,bar_width,align="center")
plt.bar(x+bar_width, Sh, bar_width, align="center",tick_label=str1)
# 展示图片
plt.show()
2.6 柱线混合图
代码:
x = [2, 4, 6, 8]
y = [450, 500, 200, 1000]
# 绘图
plt.bar(x=x, height=y, label='书库大全', color='steelblue', alpha=0.8)
# 在柱状图上显示具体数值, ha参数控制水平对齐方式, va控制垂直对齐方式
for x1, yy in zip(x, y):
plt.text(x1, yy + 1, str(yy), ha='center', va='bottom', fontsize=20, rotation=0)
# 设置标题
plt.title("80小说网活跃度")
# 为两条坐标轴设置名称
plt.xlabel("发布日期")
plt.ylabel("小说数量")
# 显示图例
plt.legend()
# 画折线图
plt.plot(x, y, "r", marker='*', ms=10, label="a")
plt.xticks(rotation=45)
plt.legend(loc="upper left")
plt.savefig("a.jpg")
plt.show()
2.7 折线图2
代码:
x = [1, 2, 3, 4]
y = [10, 50, 20, 100]
# "r" 表示红色,ms用来设置*的大小
plt.plot(x, y, "r", marker='*', ms=10, label="a")
# plt.plot([1, 2, 3, 4], [20, 30, 80, 40], label="b")
plt.xticks(rotation=45)
plt.xlabel("发布日期")
plt.ylabel("小说数量")
plt.title("80小说网活跃度")
# upper left 将图例a显示到左上角
plt.legend(loc="upper left")
# 在折线图上显示具体数值, ha参数控制水平对齐方式, va控制垂直对齐方式
for x1, y1 in zip(x, y):
plt.text(x1, y1 + 1, str(y1), ha='center', va='bottom', fontsize=20, rotation=0)
plt.savefig("a.jpg")
plt.show()
2.8 多折线图
代码:
x = [1, 2, 3, 4]
y1 = [45, 50, 20, 100]
y2 = [26, 10, 76, 25]
y3 = [11, 66, 55, 88]
y4 = [69, 50, 35, 100]
plt.plot(x, y1, marker='*', ms=10, label="C++")
plt.plot(x, y2, marker='*', ms=10, label="Java")
plt.plot(x, y3, marker='*', ms=10, label="Python")
plt.plot(x, y4, marker='*', ms=10, label="Html")
plt.xticks(rotation=45)
plt.xlabel("发布日期")
plt.ylabel("小说数量")
plt.title("80小说网活跃度")
plt.legend(loc="upper left")
# 在折线图上显示具体数值, ha参数控制水平对齐方式, va控制垂直对齐方式
for y in [y1, y2, y3, y4]:
for x1, yy in zip(x, y):
plt.text(x1, yy + 1, str(yy), ha='center', va='bottom', fontsize=20, rotation=0)
plt.savefig("a.jpg")
plt.show()
2.9 直方图
代码:
mu = 100
sigma = 20
x = mu + sigma * np.random.randn(20000) # 样本数量
plt.hist(x,bins=100,color='green') # bins显示有几个直方,normed是否对数据进行标准化
plt.show()
2.10 自定义折线图
代码:
x = np.linspace(-10,10,100)
y = x**3
plt.plot(x,y,linestyle='--',color='green',marker='<')
plt.show()
2.11 散点图
代码:
x = np.random.randn(1000)
y = x+np.random.randn(1000)*0.5
plt.scatter(x,y,s=5,marker='<') # s表示面积,marker表示图形
plt.show()
2.12 横向柱状图
代码:
fig, ax = plt.subplots()# 函数用于创建子图
people = ("北京", "上海", "深圳")
y_pos = np.arange(len(people))
ax.set_title("城市对比")
ax.set_xlabel("宜居性")# 设置横坐标单位为"performance"
performance = 2 + 10*np.random.rand(len(people))
ax.barh(y_pos, performance, color = "green",tick_label=people)
plt.show()
3、综合应用实例
线上效果图,用图表统计一个程序的崩溃率,左上角是图例说明,X轴是时间轴,Y轴是崩溃率
from pickle import NONE
import matplotlib.pyplot as plt
import numpy as np
import os
import pandas as pd
import json
import sys
crash_rates = []
exitcrash_rates = []
livecrash_rate = []
unuse_browser_rate = []
standard_rate = []
standard_rate2 = []
#赋值代码删除了,自行补充
#crash_rates.append(0.12)
#...
##end
# 下面三行为查看当前系统支持的字体有哪些,选一个添加下方plt.rc()函数中第二个参数中,不行就换一个试试
# from matplotlib import font_manager
# print("List of all fonts currently available in the matplotlib:\n")
# print(*font_manager.findSystemFonts(fontpaths=None, fontext='ttf'), sep="\n")
plt.rc("font", family='simhei')
plt.rcParams['font.size'] = 8 # 字体大小
ff = len(livecrash_rate)
xx = list(range(ff))
plt.plot(xx, livecrash_rate, "#FF0000", marker='v', ms=5, label="直播crash")
plt.plot(xx, crash_rates, "#0000FF", marker='*', ms=2, label="总crash")
plt.plot(xx, exitcrash_rates, "#00FFFF", marker='.', ms=2, label="退出crash")
plt.plot(xx, unuse_browser_rate, "#00FF00", marker='.', ms=2, label="未使用浏览器")
plt.plot(xx, standard_rate, "#ff0000", linestyle='--', ms=1, label="1号基准线 0.001")
plt.plot(xx, standard_rate2, "#ff0000",linestyle='--', ms=1, label="2号基准线 0.01")
plt.legend(loc="upper left")
# plt.savefig("a.jpg")
plt.show()
4、其他
plt.plot函数使用说明
plt.plot(x, y, format_string, **kwargs)
| 参数 | 说明 |
|---|---|
x | X轴数据,列表或数组,可选 |
y | Y轴数据,列表或数组 |
format_string | 控制曲线的格式字符串,可选 |
**kwargs | 第二组或更多(x,y,format_string),可画多条曲线 |
format_string 由颜色字符、风格字符、标记字符组成
-
颜色字符
'b'蓝色'm'洋红色 magenta'g'绿色'y'黄色'r'红色'k'黑色'w'白色'c'青绿色 cyan'#008000'RGB某颜色'0.8'灰度值字符串- 多条曲线不指定颜色时,会自动选择不同颜色
-
风格字符
'‐'实线'‐‐'破折线'‐.'点划线':'虚线'' ' '无线条
-
标记字符
'.'点标记','像素标记(极小点)'o'实心圈标记'v'倒三角标记'^'上三角标记'>'右三角标记'<'左三角标记...等等