#本章主要讨论matplotlib的绘图模块pyplot
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
#保存图形
x=np.linspace(-6, 6,100)#-6到6的100个等差数列
y=np.sin(x)
plt.plot(x,y)#绘制线图
plt.savefig('D:\Desktop\myfigure.png')
#一页多图
dose = [20,30,40,45,60]
drugA=[16,20,27,40,60]
drugB=[15,18,25,31,40]
#创建一个2行2列的网格,绘制4个子图
plt.subplot(2,2,1)#创建子图,2行2列索引1
plt.plot(dose, drugA,'o')
plt.subplot(2,2,2)
plt.plot(dose, drugB,'o')
plt.subplot(2,2,3)
plt.plot(drugA,drugB,'o')
plt.subplot(2,2,4)
plt.plot(dose,drugA,'o-')
plt.plot(dose,drugB,'o--')
plt.legend(['drugA','drugB'])
plt.show()
#还可以面向对象的绘图方式一页多图。
fig=plt.figure()#打开空白画布
ax1=fig.add_subplot(2,2,1)#创建2行2列的多图中的第1个子图画布
ax2=fig.add_subplot(2,2,2)
ax3=fig.add_subplot(2,2,3)
ax1.plot(dose,drugA,'o')#绘制第1个子图
ax2.plot(dose,drugB,'^')
ax3.plot(dose,drugA,marker='o',linestyle='-')#绘制第3个子图
ax3.plot(dose,drugB,marker='^',linestyle='--')#绘制第3个子图
ax3.legend(['drugA','drugB'])
plt.show() #显示图形
#简单折线图
# x,y轴的数据生成
x = np.linspace(0, 10, 100)
y = np.sin(x)
# fig和ax:创建图形和坐标轴;设置了图形的大小为宽度为12英寸,高度为4英寸)
fig, ax = plt.subplots(figsize=(12, 4))
# 绘制曲线,设置y轴标签和曲线颜色
ax.plot(x, y, label='sin(x)',color='red')
# 添加标题和标签
ax.set_title('Sine Wave')
ax.set_xlabel('x')
ax.set_ylabel('sin(x)')
# 添加图例,为了使图例显示
ax.legend()
# 显示图形
plt.show()
#多条折线图
# plt.rcParams是Matplotlib库中的一个字典对象,用于管理全局配置设置
plt.rcParams["font.sans-serif"]=["SimHei"] #设置字体
#该语句解决图像中的“-”负号的乱码问题,在一些中文环境下负号显示为方块或乱码
plt.rcParams["axes.unicode_minus"]=False
fig, ax = plt.subplots(figsize=(12, 4),dpi=80) #dpi是图表分辨率
x = ['第一季度','第二季度','第三季度','第四季度']
y1 = [288,197,456,210]
y2 = [110,256,376,121]
y3 = [260,356,277,300]
plt.plot(x, y1, label = 'Line1',marker='o')#实心圆点
plt.plot(x, y2, label = 'Line2', marker='*')#星形
plt.plot(x, y3, label = 'Line3',marker='^')#上三角形
plt.legend()
plt.show()
#循环实现多条折线图
# 定义数据
x = [1, 2, 3, 4, 5]
y_list = [[1, 4, 9, 16, 25], [1, 2, 3, 4, 5], [5, 4, 3, 2, 1]]
y_marker = ['*','o','^']
# 创建画布
plt.figure(figsize=(8, 4), dpi=100)
# 循环绘制每一条折线图
for i in range(len(y_list)):
plt.plot(x, y_list[i],marker=y_marker[i])
# 显示图形
plt.show()
#实现不连续的折线图
x = [1, 2, 3, 4, 5]
y = [1, 4, 9, 16, 25]
plt.plot(x, y, linestyle='--')
plt.show()
#区域填充的折线图
x = [1, 2, 3, 4, 5]
y = [1, 4, 9, 16, 25]
plt.plot(x, y)
plt.fill_between(x, y, color='gray', alpha=0.5)
plt.show()
#实例:绘制折线图
plt.rcParams["font.sans-serif"]=["SimHei"] #设置了字体为中文(宋体)
plt.rcParams["axes.unicode_minus"]=False #正常显示负号
year = [2017, 2018, 2019, 2020]
people = [20, 40, 60, 70]
#生成图表
plt.plot(year, people)
plt.xlabel('年份')
plt.ylabel('人口')
plt.title('人口增长')
#设置纵坐标刻度
plt.yticks([0, 20, 40, 60, 80])
#设置填充选项:参数分别对应横坐标,纵坐标,纵坐标填充起始值,填充颜色
plt.fill_between(year, people, 20, color = 'green')
#显示图表
plt.show()
#基础直方图
# 准备数据,生成一个包含1000个从标准正态分布中随机抽取的数值的NumPy数组
data = np.random.randn(1000)
# 绘制直方图
plt.hist(data)
#bins直方图将数据分成30个等宽的区间,edgecolor条形边缘的颜色
#plt.hist(data, bins=30, color='skyblue', edgecolor='black')
# 添加标签和标题
plt.xlabel('Value')
plt.ylabel('Frequency')
plt.title('Histogram')
# 显示图表
plt.show()
#一图多形
# 生成随机数据
np.random.seed(0)#设置随机种子
data1 = np.random.normal(0, 1, 1000)
data2 = np.random.normal(2, 1, 800)
data3 = np.random.normal(-2, 1, 1200)
# 绘制直方图
plt.hist(data1, bins=30, alpha=0.5, label='Data 1')
plt.hist(data2, bins=30, alpha=0.5, label='Data 2')#alpha透明度
plt.hist(data3, bins=30, alpha=0.5, label='Data 3')
# 添加标签和标题
plt.xlabel('Value')
plt.ylabel('Frequency')
plt.title('Histogram Comparison')
# 添加图例
plt.legend()
# 显示图表
plt.show()
#简单柱状图
x = ['A', 'B', 'C', 'D']
y = [10, 15, 7, 12]
plt.bar(x, y)
plt.xlabel('X轴')
plt.ylabel('Y轴')
plt.title('基本柱状图')
plt.show()
#实例
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
# 准备数据:电影名字
movie_name = ['雷神3:诸神黄昏','正义联盟','东方快车谋杀案','寻梦环游记','全球风暴','降魔传','追捕','七十七天','密战','狂兽','其它']
# 横坐标
x = range(len(movie_name))
# 票房数据
y = [73853,57767,22354,15969,14839,8725,8716,8318,7916,6764,52222]
# 1.创建画布
plt.figure(figsize=(20, 8), dpi=100)
# 2.绘制柱状图
plt.bar(x, y, width=0.5, color=['b','r','g','y','c','m','y','k','c','g','b'])
# 2.1b修改x轴的刻度显示
plt.xticks(x, movie_name)
# 2.2 添加网格显示
plt.grid(linestyle="--", alpha=0.5)
# 2.3 添加标题
plt.title("电影票房收入对比")
# 3.显示图像
plt.show()
#多个柱状图
x = ['A', 'B', 'C', 'D']
y1 = [10, 15, 7, 12]
y2 = [8, 11, 9, 14]
width = 0.35#width定义了柱子的宽度
x_indexes = np.arange(len(x))
#对柱状图进行定位
plt.bar(x_indexes - width/2, y1, width=width, label='柱状图1')
plt.bar(x_indexes + width/2, y2, width=width, label='柱状图2')
plt.xlabel('X轴')
plt.ylabel('Y轴')
plt.title('多个柱状图')
plt.xticks(x_indexes, x)#修改x轴刻度
plt.legend()#添加图例,将每组数据对应的柱状图标签显示出来。
plt.show()
x = ['A', 'B', 'C', 'D']
y1 = [10, 15, 7, 12]
y2 = [8, 11, 9, 14]
y3 = [6, 12, 9, 14]
width = 0.25 # 柱子的宽度
x_indexes = np.arange(len(x))
plt.bar(x_indexes - width, y1, width=width, label='柱状图1')
plt.bar(x_indexes, y2, width=width, label='柱状图2')
plt.bar(x_indexes + width, y3, width=width, label='柱状图3')
plt.xlabel('X轴')
plt.ylabel('Y轴')
plt.title('多个柱状图')
plt.xticks(x_indexes, x)
plt.legend()
plt.show()
#堆叠柱状图
x = ['A', 'B', 'C', 'D']
y1 = [10, 15, 7, 12]
y2 = [8, 11, 9, 14]
x_indexes = np.arange(len(x))
plt.bar(x_indexes, y1, label='柱状图1')
plt.bar(x_indexes, y2, bottom=y1, label='柱状图2')#bottom底部
plt.ylabel('Y轴')
plt.title('堆叠柱状图')
plt.xticks(x_indexes, x)
plt.legend()
plt.show()
#水平柱状图
y = ['A', 'B', 'C', 'D']
x = [10, 15, 7, 12]
plt.barh(y, x)
plt.xlabel('X轴')
plt.ylabel('Y轴')
plt.title('水平柱状图')
plt.show()
#带误差线的柱状图
# 1. 生成数据
#设置了随机数生成器的种子,确保每次运行代码时生成的随机数相同,以便结果可复现。
np.random.seed(20230811)
x = np.arange(10)#生成0-9等差数列
y = np.random.randint(20, 100, 10)#20到99之间的随机整数包含10个。
yerr = np.random.randint(3, 10, 10)#10个随机整数的数组,这些随机整数的范围在3到10之间,用作误差线的长度。
# 2. 创建画布
fig = plt.figure(figsize=(6, 4), dpi=100)
ax = fig.add_subplot(111)#创建了一个子图,1行1列,当前子图为第一个子图
# 3. 绘制柱形图
ax.bar(x, y, width=0.5, color='C0', yerr=yerr, capsize=5)#capsize误差线两端带有帽子,帽子的大小为5
# 4. 设置样式
ax.grid(axis='y', linestyle='--')# 为 y 轴添加网格线,并设置网格线样式为虚线
ax.set_axisbelow(True)#设置网格线在图形元素之下
ax.spines[['right', 'top']].set_color('C7')#设置右侧和顶部的坐标轴线的颜色为 'C7'(灰色)
plt.show()
#饼状图
#1、基础实心饼状图
plt.figure(figsize=(6,3), dpi=300)
labels = ['A', 'B', 'C', 'D']#定义了饼图的每个部分的标签
sizes = [15, 30, 45, 10]#定义了饼图的每个部分的大小(百分比)
plt.pie(sizes, labels=labels)
#axis是一个用于控制图形坐标轴显示和范围的重要属性:
plt.axis('equal')#设置坐标轴刻度的比例为相等,以确保饼图是一个圆形
plt.legend()
plt.show()
#2、加强版实心饼状图
# 设置字体以便支持中文
plt.rcParams['font.sans-serif'] = ['SimHei']#设置了字体为中文(宋体)
plt.rcParams['axes.unicode_minus'] = False#解决了负号显示问题
# 设置图片大小和分辨率
plt.figure(figsize=(6,3), dpi=400)
labels = ['A', 'B', 'C', 'D']
sizes = [15, 30, 45, 10]
#突出显示某一块
explode = (0, 0.1, 0, 0)
#设置颜色
colors = ['red', 'green', 'blue', 'yellow']
# autopct参数设置显示图中百分比,autopct='%1.1f%%':包含1位小数浮点型
plt.pie(sizes, labels=labels,explode=explode,colors=colors,autopct='%1.1f%%')
plt.axis('equal')
plt.title('占比图')
plt.legend()
plt.show()
#箱型图
#创建三个包含100个随机数的数据集
data1 = np.random.randn(100)
data2 = np.random.randn(100)
data3 = np.random.randn(100)
data = [data1, data2, data3]
labels = ['Group 1', 'Group 2', 'Group 3']
colors = [1, 0, 0.5]#RGB,红(R=1),绿(G=0),和蓝(B=0.5)构成
#vert=True 表示箱线图垂直排列
#patch_artist=True 表示箱线图中的箱体会使用颜色填充
#boxprops=dict(facecolor=colors) 则用于设置箱体的颜色
plt.boxplot(data, labels=labels, vert=True, patch_artist=True, boxprops=dict(facecolor=colors))
plt.show()
#散点图
#创建一个散点图来显示鸢尾花不同种类之间的萼片长度和宽度的关系
from sklearn.datasets import load_iris#加载iris数据集
iris = load_iris()#存储在iris变量
types = iris.target_names#目标类别名称存储在types变量中
colors = ['red', 'blue', 'green']
# 创建一个DataFrame以更好地操作数据
#创建一个数据帧(DataFrame),将鸢尾花数据集的特征数据存储在其中,并使用特征名称作为列名。
df = pd.DataFrame(iris.data, columns=iris.feature_names)
#在数据帧(DataFrame)中创建一个名为species的新列,该列使用目标值和目标类别名称来表示鸢尾花的种类。
df['species'] = pd.Categorical.from_codes(iris.target, types)
for i in range(len(types)):
plt.scatter(df.loc[df['species'] == types[i], 'sepal length (cm)'],
df.loc[df['species'] == types[i], 'sepal width (cm)'],
color=colors[i],
label=types[i])
plt.legend()
plt.xlabel('Sepal Length (cm)')
plt.ylabel('Sepal Width (cm)')
plt.show()
#简单热力图
plt.figure(figsize=(10,6), dpi=100)
#创建一个包含不同蔬菜名称的列表
vegetables = ["cucumber", "tomato", "lettuce", "asparagus",
"potato", "wheat", "barley"]
#创建一个包含不同农民名称的列表。
farmers = ["Farmer Joe", "Upland Bros.", "Smith Gardening",
"Agrifun", "Organiculture", "BioGoods Ltd.", "Cornylee Corp."]
#创建一个7x7的NumPy数组,表示每个农民种植每种蔬菜的收获量。
harvest = np.array([[0.8, 2.4, 2.5, 3.9, 0.0, 4.0, 0.0],
[2.4, 0.0, 4.0, 1.0, 2.7, 0.0, 0.0],
[1.1, 2.4, 0.8, 4.3, 1.9, 4.4, 0.0],
[0.6, 0.0, 0.3, 0.0, 3.1, 0.0, 0.0],
[0.7, 1.7, 0.6, 2.6, 2.2, 6.2, 0.0],
[1.3, 1.2, 0.0, 0.0, 0.0, 3.2, 5.1],
[0.1, 2.0, 0.0, 1.4, 0.0, 1.9, 6.3]])
#设置x轴刻度标签为农民的名称,并将刻度标签旋转45度,使其更易读
plt.xticks(np.arange(len(farmers)), labels=farmers,
rotation=45, rotation_mode="anchor", ha="right")
#设置y轴刻度标签为蔬菜的名称
plt.yticks(np.arange(len(vegetables)), labels=vegetables)
#设置图表标题为“当地农民的收获量(单位:吨/年)
plt.title("Harvest of local farmers (in tons/year)")
#使用嵌套循环遍历每个蔬菜和农民的组合
#在热力图的每个单元格中显示对应的收获量,并将文本居中显示
for i in range(len(vegetables)):
for j in range(len(farmers)):
text = plt.text(j, i, harvest[i, j], ha="center", va="center", color="w")
#使用热力图方式呈现收获量的数据
plt.imshow(harvest)
#添加一个颜色条,用于解释颜色与数据值之间的对应关系。
plt.colorbar()
#调整子图之间的间距,以便图表呈现更美观
plt.tight_layout()
plt.show()