统计图
折线图
示例1
import matplotlib
from matplotlib import pyplot as plt
font = {'family': 'SimHei', 'weight': 'bold', 'size': 12}
matplotlib.rc('font', **font)
x = list(range(1, 6))
y = [i ** 2 for i in x]
# 设置绘图窗口尺寸
plt.figure(figsize=(10, 6), dpi=80)
# 设置标题
plt.title("Square Number", fontsize=20)
# 设置x和y轴标题
plt.xlabel("X", fontsize=14)
plt.ylabel("Y", fontsize=14)
plt.tick_params(axis="both", labelsize=14)
# 设置坐标轴的刻度
plt.xticks(x)
plt.yticks(range(0, 25, 2))
# 关闭坐标轴
# plt.axis('off')
# 绘制曲线
plt.plot(x, y, color='red')
# 绘制点
"""参数
s: 点的大小,c代表点的颜色
camp: 点的映射,具体意思是y越大颜色越深;
edgecolors: 边缘颜色
marker: 点的展示样式"""
plt.scatter(x, y, s=200, c=y, cmap="Blues", edgecolors='none', marker='*')
# 保存图片:一定放在展示图片show()方法之前
# plt.savefig("./resource/xxx.png")
# 展示图片
plt.show()
示例2
import matplotlib
from matplotlib import pyplot as plt
font = {"family": "SimHei", "weight": "bold", "size": 12}
matplotlib.rc("font", **font)
x = range(11, 31)
y = [1, 1, 1, 1, 2, 4, 3, 2, 3, 4, 4, 5, 6, 5, 4, 3, 3, 1, 1, 1]
y_1 = [0, 2, 4, 1, 1, 2, 1, 2, 3, 2, 1, 3, 1, 2, 4, 1, 2, 1, 0, 1]
plt.figure(figsize=(12, 8), dpi=80)
_xticks_label = ["{}岁".format(i) for i in x]
plt.xticks(x, _xticks_label)
plt.xlabel("年龄")
plt.ylabel("男\女朋友个数")
plt.title("交友数量")
# 绘制网格
plt.grid()
# 设置图例(那条曲线代表哪个人)
plt.plot(x, y, label="同学")
plt.plot(x, y_1, label="我")
# 只要设置图例,要想让它显示必须写这个东西
plt.legend(prop=font)
plt.show()
散点图
示例1
import matplotlib
import numpy as np
from matplotlib import pyplot as plt
font = {'family': 'SimHei', 'weight': 'bold', 'size': 12}
matplotlib.rc('font', **font)
x = np.random.normal(0, 1, 500)
y = np.random.normal(0, 1, 500)
# 参数alpha代表透明度
plt.scatter(x, y, s=40, color='blue', alpha=0.5)
# 去掉坐标轴的文字信息
plt.xticks(())
plt.yticks(())
plt.legend(loc='best')
plt.show()
示例2
import random
import matplotlib
from matplotlib import pyplot as plt
font = {"family": "SimHei", "weight": "bold", "size": 12}
matplotlib.rc("font", **font)
# 设置标题和轴标题
plt.title("三月份和十月份气温")
plt.xlabel("日期")
plt.ylabel("气温")
# 制造数据
x_3 = range(1, 32)
y_3 = [random.randint(1, 19) for i in range(1, 32)]
x_10 = range(51, 82)
y_10 = [random.randint(10, 29) for i in range(1, 32)]
# 绘制点
"""参数
label: 图例时使用
"""
plt.scatter(x_3, y_3, label="三月份")
plt.scatter(x_10, y_10, label="十月份")
# x轴添加刻度值
_x = (list(x_3) + list(x_10))[::3]
_xtick_labels = ['3月{}日'.format(i) for i in x_3]
_xtick_labels += ['10月{}日'.format(i) for i in x_10]
plt.xticks(_x, _xtick_labels[::3], rotation=45)
# 添加图例
plt.legend(loc='best')
plt.show()
示例3
from random import choice
import matplotlib.pyplot as plt
class RandomWalk(object):
"""一个随机漫步数据"""
def __init__(self, num_points=500):
"""初始化随机漫步的属性"""
self.num_points = num_points
# 所有随机漫步都始于(0,0),用列表存储x和y
self.x_value = [0]
self.y_value = [0]
def walk(self):
""""计算随机漫步包含的所有点"""
# 不断循环,直到到达指定的长度
while len(self.x_value) < self.num_points:
# 决定前进的方向及距离
x_direction = choice([1, -1]) # 随即方向
x_distance = choice([0, 1, 2, 3, 4, 5]) # 随即距离
x_march = x_direction * x_distance
y_direction = choice([1, -1]) # 随即方向
y_distance = choice([0, 1, 2, 3, 4, 5]) # 随即距离
y_march = y_direction * y_distance
# 防止在原地踏步
if x_march == 0 and y_march == 0:
continue
# 计算下一个点的x和y的值
x_next = self.x_value[-1] + x_march
y_next = self.y_value[-1] + y_march
self.x_value.append(x_next)
self.y_value.append(y_next)
if __name__ == '__main__':
# 创建walk的实例并绘制点
wk = RandomWalk()
wk.walk()
plt.scatter(wk.x_value, wk.y_value, color="red")
plt.title("Square Numbers", fontsize=12)
plt.xlabel("X", fontsize=24)
plt.ylabel("Y", fontsize=24)
# plt.tick_params(axis="both", which="major", labelsize=14) # 设置刻度大小
# 绘制
plt.show()
竖直条形图
import matplotlib
from matplotlib import pyplot as plt
font = {'family': 'SimHei', 'weight': 'bold', 'size': 12}
matplotlib.rc('font', **font)
x = list(range(1, 6))
y = [i ** 2 for i in x]
# 绘制条形图
"""参数
facecolor: 柱体颜色
edgecolor: 柱体边缘颜色
width: 柱体的宽度"""
plt.bar(x, y, facecolor='yellow', edgecolor='black', width=0.6)
# 显示每个柱的数值
"""参数
'%.2f': 保留两位小数
ha: 数值水平对齐方式
va: 数值垂直对齐方式
"""
for x, y in zip(x, y):
plt.text(x, y, '%.2f' % y, ha='center', va='bottom')
plt.show()
水平条形图
import matplotlib
from matplotlib import pyplot as plt
font = {'family': 'SimHei', 'weight': 'bold', 'size': 12}
matplotlib.rc('font', **font)
x = range(10)
y = [i ** 2 for i in x]
# 画直方图的函数
# 参数height:线条粗细
plt.barh(x, y, facecolor='orange', edgecolor='black', height=0.3)
plt.yticks(x, x)
# 绘制网格
plt.grid(alpha=0.5)
plt.show()
直方图
import matplotlib
from matplotlib import pyplot as plt
font = {'family': 'SimHei', 'weight': 'bold', 'size': 12}
matplotlib.rc('font', **font)
plt.figure(figsize=(16, 8), dpi=80)
# 制造数据
x = [98, 124, 111, 121, 106, 125, 100, 131, 114, 128]
# 组距
d = 5 # 只有当len(x)/d==0时,图像才不会出现偏移
# 组数
num_bins = (max(x) - min(x)) // d
# 绘制柱体
plt.hist(x, num_bins)
# 绘制刻度
plt.xticks(range(min(x), max(x) + d, d))
# 绘制网格
plt.grid()
plt.show()
等高线
import matplotlib
import numpy as np
from matplotlib import pyplot as plt
font = {'family': 'SimHei', 'weight': 'bold', 'size': 12}
matplotlib.rc('font', **font)
def func(x, y):
"""绘制等高线的函数"""
return (1 - x / 2 + x ** 5 + y ** 3) * np.exp(-x ** 2 - y ** 2)
x = np.linspace(-3, 3, 100)
y = np.linspace(-3, 3, 100)
# 将x,y传入一个网格中
X, Y = np.meshgrid(x, y)
# 绘制等高线
plt.contour(X, Y, func(X, Y), alpha=0.8, cmap=plt.cm.hot)
# 等高线图例(每根线条上的数值)
C = plt.contour(X, Y, func(X, Y), 8, colors='black')
plt.clabel(C, inline=False, fontsize=10) # 参数inline:数字是否在线里面
# 关闭坐标轴
plt.axis("off")
plt.show()
3D图像
import matplotlib
import numpy as np
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
font = {'family': 'SimHei', 'weight': 'bold', 'size': 12}
matplotlib.rc('font', **font)
# 生成3D坐标系
fig = plt.figure()
ax = Axes3D(fig)
# 制造数据
x = np.arange(-4, 4, 0.25)
y = np.arange(-4, 4, 0.25)
X, Y = np.meshgrid(x, y)
R = np.sqrt(X ** 2 + Y ** 2)
Z = np.sin(R)
# 渲染3D物体
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=plt.get_cmap('rainbow'))
# 将3D物体投影到地面上
"""参数
offset: 映射到x为-2的位置
cmap: 颜色为彩虹
"""
ax.contour(X, Y, Z, offset=-2, cmap='rainbow')
ax.set_zlim(-2, 2)
# 展示图像
plt.show()
子图
import matplotlib
import numpy as np
from matplotlib import pyplot as plt
font = {'family': 'SimHei', 'weight': 'bold', 'size': 12}
matplotlib.rc('font', **font)
def f(t):
return np.exp(-t) * np.cos(2 * np.pi * t)
t1 = np.arange(0, 5, 0.1)
t2 = np.arange(0, 5, 0.02)
# 可以调整subplot的参数调整多个图像的大小比例
ax = plt.subplot(2, 1, 1)
# 两个列表分别表示起点终点的x和y坐标
ax.plot([0, 1], [0, 1])
ax.set_title("子图1")
plt.subplot(2, 3, 4)
plt.plot(t1, f(t1), 'bo')
plt.subplot(2, 3, 5)
plt.plot(t2, f(t2), 'r-')
# 设置两行之间的距离,放置挤压在一起
plt.subplots_adjust(hspace=0.5)
ax1 = plt.subplot(2, 3, 6)
ax1.plot([0, 1], [0, 1])
ax1.set_xlabel("年龄")
ax1.set_ylabel("收入")
plt.show()
动态作图
import matplotlib
import numpy as np
from matplotlib import animation
from matplotlib import pyplot as plt
font = {'family': 'SimHei', 'weight': 'bold', 'size': 12}
matplotlib.rc('font', **font)
fig, ax = plt.subplots()
x = np.arange(0, 2 * np.pi, 0.01)
line = ax.plot(x, np.sin(x))
def animate(i):
"""动画曲线函数"""
line.set_ydata(np.sin(x + i / 10))
return line
def init():
"""初始化的函数"""
line.set_ydata(np.sin(x))
return line
# 生成图像
animation.FuncAnimation(fig=fig, func=animate, init_func=init, interval=20)
plt.show()
饼状图
import matplotlib
from matplotlib import pyplot as plt
font = {'family': 'SimHei', 'weight': 'bold', 'size': 12}
matplotlib.rc('font', **font)
# 制造数据
labels = ['Unity', '爬虫', 'Pygame', '数据可视化', '机器学习']
sizes = [40, 20, 20, 10, 10]
# 爆炸效果,数字代表这一块离其他的距离
explode = (0, 0.1, 0, 0, 0)
fig,ax = plt.subplots()
# 绘制饼状图
"""参数shadow:阴影,使图像有3D效果"""
ax.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%', shadow=True, startangle=90)
# 使饼状图为圆形,默认是椭圆的
ax.axis('equal') # 圆形
plt.show()
绘制函数
import matplotlib
import numpy as np
from matplotlib import pyplot as plt
font = {'family': 'SimHei', 'weight': 'bold', 'size': 12}
matplotlib.rc('font', **font)
# 制造数据,[-3,3]创建100个点
x = np.linspace(-3, 3, 100)
y0 = x * 2 + 1
y1 = x ** 2
# 设置x和y的范围
plt.xlim((-1, 2))
plt.ylim((-2, 3))
# 设置x和y的标签
plt.xlabel("X Label")
plt.ylabel("Y Label")
# 设置x和y的刻度信息
new_ticks = np.linspace(-2, 2, 11)
plt.xticks(new_ticks)
plt.yticks([-1, 0, 1, 2, 3], ['y1', 'y2', 'y3', 'y4', 'y5'])
# 如果写了一个figure,则只渲染一张图,即把多条曲线画在一幅图中,否则会画多幅图
# 参数figsize:设置图像大小,两个数字分别代表宽高
# plt.figure(figsize=(5,5))
"""参数
linewidth:线条宽度
linestyle:线条格式,'-'代表实线,'--'代表虚线,'-.'代表点线,':'代表另一种线"""
l1, = plt.plot(x, y0, color="blue", linewidth=1.0, linestyle="-")
# plt.figure(figsize=(10,10))
l2, = plt.plot(x, y1, color="red", linewidth=4.0, linestyle=':')
# 设置图例
# 注意,l1,l2参数后面要写逗号!!!
plt.legend(handles=[l1, l2], labels=['train1', 'train2'], loc='best')
# 获取当前的坐标轴
ax = plt.gca()
ax.spines['right'].set_color("none") # 设置边框颜色
ax.spines['top'].set_color("none") # 默认为无色'none'
ax.spines['bottom'].set_position(("data", 0)) # 设置零点坐标
ax.spines['left'].set_position(("data", 0)) # 设置零点坐标
ax.xaxis.set_ticks_position('bottom') # 设置坐标轴在哪个边框
ax.yaxis.set_ticks_position('left') # 默认x在bottom,y轴在left
# 画点画虚线
x0 = 0.5
y0 = x0 * 2 + 1.0
plt.scatter(x0, y0, s=50, color='blue') # 画点
plt.plot([x0, x0], [y0, 0], 'k--', linewidth=2) # 画虚线,'k--'表示黑色虚线
# 画箭头做标注
"""参数
xy:描述的点
xytest:文本左上角坐标
connectionstyle:箭头外观rad代表弧度
"""
plt.annotate(r'$2x+1={}$'.format(y0), xy=(x0, y0), xytext=(+30, -30), textcoords='offset points', fontsize=20,
arrowprops=
dict(color='orange', arrowstyle='->', connectionstyle='arc3,rad=.2'))
# 添加文字描述
# 文本中的空格需要加\转义
plt.text(-2, 3, r'$Hello\ Unity\ World!$', fontdict={'size': 13, 'color': 'green'})
plt.show()
其他问题
中文显示
-
为什么无法显示中文:
matplotlib
默认不支持中文字符,因为默认的英文字体无法显示汉字 -
修改方法:
font = {'family': 'SimHei', 'weight': 'bold', 'size': 16} plt.rc('font', **font)
plot(**kwargs)调参
x、y
:位置ls
:折现的风格(-
,--
,-.
,:
)lw
:线条宽度c
:颜色marker
:线条上点的形状markersize
:点的大小markeredgecolor
:点的边框色markerfacecolor
:点的填充色label
:文本标签