matplotlib超详细总结,可调用代码灵活运用

目录

Matplotlib介绍与环境搭建

Matplotlib简介

为什么学习Matplotlib

图表的组成

图表(Figure)

轴(Axes)

轴(Axis)

画家(Artist)

Matplotlib的安装

Matplotlib初步体验

Matplotlib的基本使用

案例

设置标签文字和线条粗细

Matplotlib中文问题

查看系统内字体

临时增加字体

设置字体

单独设置字体

Matplotlib风格

某周最高温度和最低温度变化

Matplotlib多图分布

pyplot.subplot

pyplot.subplots

Matplotlib嵌套图形

fig.add_subplot

plt.axes与fig.add_axes

Matplotlib双轴显示

Axes.twinx()

Matplotlib绘图样式

线条属性

Matplotlib设置坐标轴

单轴设置X与Y轴刻度

双轴设置y轴刻度

Matplotlib网格与标题

pyplot.grid

pyplot.title 与 pyplot.suptitle

Matplotlib绘制文本

pyplot.text方法

Matplotlib注释的使用

pyplot.annotate方法

Matplotlib保存图表

pyplot.savefig

折线图

条形(柱形)图

方法

普通条图

横向条图

多组条图

堆叠条图

直方图

概念

方法

普通直方图

修改样式

显示概率

箱图(盒图)

方法

单盒子

多盒子

散点图

方法

代码

饼图

方法

常规饼图

设置字体

互换内容位置

分离扇区

空心饼图

热力图

方法

常规热力图

带样式

3D图表

设置画布为3D

3D折线图

3D散点图

3D条图


Matplotlib介绍与环境搭建

image-20211227092118371

Matplotlib简介

Matplotlib 是一个用于绘制图表和可视化数据的 Python 库。它提供了一种类似于 MATLAB 的绘图接口,使用户能够轻松地生成各种类型的图形,包括折线图、散点图、直方图、饼图等。Matplotlib 被广泛应用于数据分析、科学计算、工程和其他领域

官网:Matplotlib — Visualization with Python

image-20240102174236610

为什么学习Matplotlib

  • 可让数据可视化,更直观的真实给用户。使数据更加客观、更具有说服力。

  • Matplotlib是Python的库,又是开发中常用的库

图表的组成

../../_images/anatomy.png

图表(Figure)

在 Matplotlib 中,Figure 是一个顶层容器,用于包含图表中的所有元素。比如坐标轴、图例、标题、等

轴(Axes)

一个 Matplotlib 图表可以包含一个或多个 Axes 对象,每个 Axes 对象都是一个独立的坐标系,可以理解成一个子图

image-20240102234638196

轴(Axis)

在 Matplotlib 中,Axis 这个词可以指代 坐标轴,即图表中的X轴和Y轴。这是用于定位和测量数据点位置的参考线

画家(Artist)

在 Matplotlib 中,Artist 是一个基础的图形元素对象,它代表了图表中的各种图形元素,如图形、文本、线条等。所有的图形元素,无论是图表本身、坐标轴、标签还是其他可见的部分,都是 Artist 对象

Matplotlib的安装

pip install matplotlib==3.8.2

Matplotlib初步体验

img

Matplotlib的基本使用

在使用Matplotlib绘制图形时,其中有两个最为常用的场景。一个是画点,一个是画线。pyplot基本方法的使用如下表

方法名说明
title()设置图表的名称
xlabel()设置x轴名称
ylabel()设置y轴名称
xticks(x,ticks,rotation)设置x轴的刻度,rotation旋转角度
yticks()设置y轴的刻度
plot()绘制线性图表
show()显示图表
legend()显示图例
text(x,y,text)显示每条数据的值 x,y值的位置
figure(name,figsize=(w,h),dpi=n)设置图片大小

案例

import matplotlib.pyplot as plt
x=[1,2,3,4,5]
squares=[1,4,9,16,25]
plt.plot(x,squares)
plt.show()

设置标签文字和线条粗细

import matplotlib.pyplot as plt
datas=[1,2,3,4,5]
squares=[1,4,9,16,25]
plt.plot(datas,squares,linewidth=5) #设置线条宽度
#设置图标标题,并在坐标轴上添加标签
plt.title('Numbers',fontsize=24)
plt.xlabel('datas',fontsize=14)
plt.ylabel('squares',fontsize=14)
plt.show()

Matplotlib中文问题

image-20240103015152175

查看系统内字体

from matplotlib.font_manager import fontManager as fm


for f in fm.ttflist:
  if f.fname.find('simhei.ttf') != -1:
    print(f.name,'===',f.fname)

临时增加字体

from matplotlib.font_manager import fontManager as fm


fm.addfont('./ali.ttf')
for f in fm.ttflist:
  if f.fname.find('ali') != -1:
    print(f.name,'===',f.fname)

设置字体

import matplotlib.pyplot as plt


#设置中文乱码问题
plt.rcParams['font.sans-serif'] = 'SimHei'
plt.rcParams['font.family']='SimHei'

单独设置字体

import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties


datas=[1,2,3,4,5]
squares=[1,4,9,16,25]
plt.plot(datas,squares) #设置线条宽度
#设置图标标题,并在坐标轴上添加标签
plt.title('标题设置',fontsize=24,fontdict={'fontproperties':FontProperties(fname='./ali.ttf')})
plt.xlabel('x轴',fontsize=14,fontdict={'family':'SimHei'})
plt.ylabel('y轴',fontsize=14,fontdict={'family':'SimHei'})

Matplotlib风格

image-20240104163803500

官方地址:matplotlib.style — Matplotlib 3.10.6 documentation

from matplotlib import style
#风格的设置
#查看有哪些风格
print(style.available)
#设置风格
style.use('ggplot')

提示

设置风格时,有可能让部分设置失效,需要重新设置

某周最高温度和最低温度变化

image-20211228163826704

 # 构造数据
max_temperature = [26, 30, 31, 32, 33]
min_temperature = [12, 16, 16, 17, 18]
x = range(5)
plt.rcParams['font.family'] = 'SimHei'
x_ticks = ['星期{}'.format(i) for i in range(1, 6)]
plt.title('某年某周第N周的温度')
plt.xlabel('周')
plt.ylabel('温度:单位(℃)')
# 设置x轴标签
plt.xticks(x, x_ticks)
# 填充数据
plt.plot(x, max_temperature, label='最高温')
plt.plot(x, min_temperature, label='最低温')
# 显示图例
plt.legend(loc=2)

Matplotlib多图分布

image-20240105102307374

pyplot.subplot

# 获得画布
fig = plt.figure(figsize=(15, 8))
# 获得子图
ax1=plt.subplot(2, 2, 1)
ax2=plt.subplot(222)
ax3=plt.subplot(223)
ax4=plt.subplot(224)
#-------------------------------
fig = plt.figure(figsize=(15, 8))
# 获得子图
ax1=plt.subplot(2, 2, 1)
ax2=plt.subplot(222)
ax3=plt.subplot(212)
ax1.plot([1,2,3,4],[1,2,3,4])
# 给ax1设置标题
ax1.set_title('ax1')

pyplot.subplots

fig = plt.figure()
ax = plt.subplots(2,2,figsize=(28, 8))
display(ax)
#--------------------------------
fig = plt.figure(figsize=(15, 8))
ax = fig.subplots(2,2)
display(ax)

Matplotlib嵌套图形

image-20240105104018963

fig.add_subplot

fig = plt.figure(figsize=(15, 8))
ax = fig.add_subplot(1,1,1)
plt.plot([1,2,3,4],[1,2,3,4])
ax2 = fig.add_subplot(2,3,1)
ax2.plot([1,2,3,4],[1,2,3,4])

plt.axes与fig.add_axes

fig = plt.figure(figsize=(15, 8))
plt.plot([1,2,3,4],[1,2,3,4])
plt.axes([0.2,0.6,0.2,0.2])
fig.add_axes([0.6,0.2,0.2,0.2])

Matplotlib双轴显示

parasite simple

Axes.twinx()

创建共享 x 轴的双轴

from matplotlib import pyplot as plt


plt.rcParams['font.sans-serif'] = 'SimHei'


times = range(12)
# 1天24小时气温变化
data1= [15, 13, 14, 17, 20, 22, 23, 22, 21, 19, 18, 16]
# 1天24小时湿度变化
data2= [40, 42, 45, 48, 50, 55, 60, 65, 70, 75, 80, 85]
fig, ax1 = plt.subplots()


ax1.set_xlabel('时间')
ax1.set_ylabel('温度')
ax1.plot(times, data1,label='温度',color='red')


ax2 = ax1.twinx()


ax2.set_ylabel('湿度')
ax2.plot(times, data2,label='湿度',color='blue')
fig.legend(loc=1)
fig.tight_layout()
import matplotlib.pyplot as plt


fig = plt.figure()
ax1 = plt.subplot(111)
ax2 = ax1.twinx()


ax1.set_xlabel("距离")
ax1.set_ylabel("密度")
ax2.set_ylabel("温度")


ax1.plot([0, 1, 2], [0, 1, 2], label="密度")
ax2.plot([0, 1, 2], [10, 13, 12], label="温度")


fig.legend()

Matplotlib绘图样式

image-20240108143454613

线条属性

  • color颜色

  • linewith宽度

  • linestyle样式

  • alpha透明度

  • marker标记

  • mfc:make face color 标记的背景颜色

import matplotlib.pyplot as plt


fig = plt.figure()
ax1 = plt.subplot(111)
ax2 = ax1.twinx()


ax1.set_xlabel("Distance")
ax1.set_ylabel("Density")
ax2.set_ylabel("Temperature")


ax1.plot([0, 1, 2], [0, 1, 2], label="Density",color='red',marker='o',linestyle='solid',mfc='b',markersize=10,markeredgecolor='g',markeredgewidth=1,)
ax2.plot([0, 1, 2], [10, 13, 12], label="Temperature",c='b',marker='v',alpha=0.3,)


fig.legend()

Matplotlib设置坐标轴

image-20240108165806982

图表坐标轴是用来显示和表示数据的数值在图表中的位置的线性轴线。坐标轴有两个方向:水平轴(X轴)和垂直轴(Y轴)

单轴设置X与Y轴刻度

# 1. 准备数据
data = [1,3,5,7,9,11,13,15,17,19]
x = range(len(data))
# 2. 绘制图形
plt.plot(x,data)
# 3. 设置x轴刻度
x_tick = ['第{}天'.format(i) for i in range(1,11)]
plt.xticks(x,x_tick)
plt.yticks(range(0,20,2))
plt.show()

双轴设置y轴刻度

Matplotlib网格与标题

image-20240109012303147

pyplot.grid

# 1. 准备数据
# 1天的温度
data = [-5, 1, 3, 6, 9, 10, 8, 7, 4, 2]
# 时间
x = range(1, 11)
# 绘制图像
plt.plot(x, data)
plt.grid(axis='x',c='gray',lw=0.5,ls='--',alpha=0.5)

pyplot.title 与 pyplot.suptitle

# 1. 准备数据
# 1天的温度
data = [-5, 1, 3, 6, 9, 10, 8, 7, 4, 2]
# 时间
x = range(1, 11)
# 绘制图像
plt.plot(x, data)
plt.title('1天的温度变化',fontsize=12)
plt.suptitle('2030年10月1日',fontsize=20)

Matplotlib绘制文本

image-20240109151223603

pyplot.text方法

from matplotlib import pyplot as plt


plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False


# 1.设置网格
data = [-5,1,3,6,9,10,8,4,3,2,0,-2,-4]
x = range(1,len(data)+1)


plt.plot(x,data,marker='o',ls='--')
for i,j in zip(x,data):
  # ha水平对齐方式   va垂直对齐方式
  plt.text(i+0.3,j,j,fontsize=10,color='tab:red',ha='center',va='center')

Matplotlib注释的使用

image-20240109161950045

pyplot.annotate方法

from matplotlib import pyplot as plt


plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False


data = [-5,1,3,6,9,10,8,4,3,2,0,-2,-4]
x = range(1,len(data)+1)


min_data = min(data)
min_index = data.index(min_data)+1


plt.plot(x,data,marker='o',linestyle='--')
plt.annotate('最小值',xy=(min_index,min_data),
       xytext=(min_index+1,min_data+1),   arrowprops=dict(facecolor='black',shrink=0.2,width=2,headwidth=6,headlength=5))

Matplotlib保存图表

image-20240109170428069

pyplot.savefig

from matplotlib import pyplot as plt


plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False


data = [-5,1,3,6,9,10,8,4,3,2,0,-2,-4]
x = range(1,len(data)+1)


plt.plot(x,data,marker='o',ls='--')
plt.savefig('./img/line1.png')
plt.savefig('./img/line2.svg')
plt.savefig('./img/line3.jpeg')
plt.savefig('./img/line4.pdf')
plt.savefig('./img/line5.png',dpi=300)
plt.savefig('./img/line6.png',dpi=600,facecolor='gray')
plt.savefig('./img/line6.png',pad_inches=2)

折线图

image-20240109220353147

折线图是一种常用的数据可视化工具,它主要用于展示随时间或有序类别变化的数据趋势。以下是折线图的主要作用和适用场景:

image-20240110140501981

  1. 显示趋势: 折线图非常适合展示数据随时间变化的趋势。通过将数据点连接起来,可以清晰地看到数据的增长、下降或波动趋势,帮助观察者理解数据的发展过程

  2. 突出波动和变化: 折线图可以有效地显示数据的波动和变化。观察者可以通过折线的上下波动来了解数据的不稳定性或周期性变化

  3. 比较多组数据: 如果你想比较多组数据在相同时间或 条件下的变化趋势,折线图是一个有用的工具。通过在同一图表上绘制多条折线,可以清晰地比较它们之间的差异

  4. 突出异常值: 折线图有助于识别数据中的异常值。当有一个数据点与其周围的趋势不一致时,很容易在折线图中看到这种异常

  5. 预测趋势: 基于历史数据的趋势,折线图可以用于预测未来的趋势。这对于业务决策和规划具有重要意义

  6. 显示周期性变化: 如果数据具有周期性的变化,例如季节性变化或周期性事件,折线图可以很好地展示这种周期性

from matplotlib import pyplot as plt


plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False


# 1.准备数据
data=['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
x = [1,2,3,4,5,6,7]
max_data = [10, 11, 13, 11, 12, 12, 9]
min_data = [1, -2, 2, 5, 3, 2, 0]


# 绘制图表
plt.plot(x,max_data,label='最高温度',marker='o',mfc='w',linestyle='--',markeredgecolor='tab:orange')
plt.plot(x,min_data,label='最低温度',marker='*',mfc='w',linestyle=':',markeredgecolor='tab:green')
# 后续设置x轴刻度
plt.xticks(x,data)
# 显示图例
plt.legend()
# 设置网格
plt.grid(axis='y',linestyle='--',alpha=0.5)
# 设置y轴刻度
plt.yticks(range(-2,15,2))
# 设置标题
plt.title('一周温度变化图')

条形(柱形)图

image-20211227095357536

条形图是一种常见的数据可视化工具,它主要用于比较不同类别之间的数据。以下是条形图的主要作用和适用场景:

  1. 比较类别之间的大小: 条形图适用于展示不同类别的数据量或大小,通过条形的长度直观地比较它们之间的差异

  2. 展示排名和排序: 条形图可以用于显示数据的排名顺序,使观察者能够很容易地识别出最大值、最小值以及中间的排名

  3. 展示分布情况: 当你想了解不同类别在整体中所占的比例或分布情况时,条形图是一种有效的选择。每个条形的长度代表相应类别的数据量,总和即为整体的总量

  4. 呈现时间趋势: 虽然折线图更适合显示时间趋势,但条形图也可用于呈现时间点上的数据,例如某个特定时间内的销售额或收益

  5. 对比多组数据: 类似于折线图,条形图也能用于对比多组数据,但通常是在不同类别上进行比较,而非随时间变化

  6. 突出异常值: 条形图可以突出显示数据的异常值,观察者可以很容易地识别出高于或低于平均水平的类别

方法

  • bar(x,y,color,width) 纵向条形图

  • barh(x,y,color,height) 横向条形图

普通条图

import matplotlib.pyplot as plt


fig, ax = plt.subplots()


fruits = ['苹果', '蓝莓', '草莓', '橘子']
counts = [40, 100, 30, 55]


bar_labels = ['青红色', '蓝色', '红色', '橙色']
bar_colors = ['tab:red', 'tab:blue', 'orangered', 'tab:orange']


container = ax.bar(fruits, counts, label=bar_labels, color=bar_colors)
ax.bar_label(container)
ax.set_ylabel('水果数量')
ax.set_title('按种类和颜色划分的水果供应')
ax.legend(title='水果颜色')

横向条图

import matplotlib.pyplot as plt


fig, ax = plt.subplots()


fruits = ['苹果', '蓝莓', '草莓', '橘子']
counts = [40, 100, 30, 55]


bar_labels = ['青红色', '蓝色', '红色', '橙色']
bar_colors = ['tab:red', 'tab:blue', 'orangered', 'tab:orange']


container = ax.barh(fruits, counts, label=bar_labels, color=bar_colors)


ax.bar_label(container)
ax.set_xlabel('水果数量')
ax.set_title('按种类和颜色划分的水果供应')
ax.legend(title='水果颜色')

多组条图

import matplotlib.pyplot as plt


species = ("苹果","蓝莓","橘子")
weight_counts = {
  "第1季度": [70, 39, 58],
  "第2季度": [82, 37, 66],
}
x = range(len(species))
x1 =[_+width for _ in x]
width = 0.2
container = plt.bar(x, weight_counts["第1季度"],color='tab:red',label='第1季度',width=width)
plt.bar_label(container)
container2 = plt.bar(x1, weight_counts["第2季度"],color='tab:blue',label='第2季度',width=width)
plt.bar_label(container2)
plt.xticks([_+width/2 for _ in x], species)
plt.legend(loc=1)

堆叠条图

import matplotlib.pyplot as plt


species = ("苹果","蓝莓","橘子")
weight_counts = {
  "第1季度": [70, 39, 58],
  "第2季度": [82, 37, 66],
}
x = range(len(species))
container = plt.bar(x, weight_counts["第1季度"],color='tab:red',label='第1季度')
plt.bar_label(container,label_type='center')
container2 = plt.bar(x, weight_counts["第2季度"],color='tab:blue',label='第2季度',bottom=weight_counts["第1季度"])
plt.bar_label(container2,label_type='center')
plt.xticks([_+width/2 for _ in x], species)
plt.legend(loc="upper right")

直方图

image-20211227100309704

直方图是一种用于展示数据分布情况的图表,主要用于描述数值型数据的频数分布。以下是直方图的主要作用和适用场景:

  1. 展示数据分布: 直方图可用于呈现数值型数据的分布情况,帮助观察者了解数据集中在哪个范围内、是否存在偏斜以及分布的形状

  2. 观察数据的集中趋势和离散程度: 通过直方图,你可以直观地看到数据的中心位置(集中趋势)和数据的分散程度(离散程度),从而更好地理解数据的整体特征

  3. 识别异常值: 直方图能够帮助你发现数据集中的异常值,即明显偏离主体的数值,这对于数据清理和异常值处理很有帮助

  4. 判断数据的对称性: 直方图的形状可以显示数据集的对称性或偏斜程度,有助于了解数据是正态分布还是偏斜分布

  5. 比较不同数据集之间的差异: 当你有多个数据集需要比较时,直方图可以清晰地展示它们的分布情况,帮助观察者理解它们之间的差异

  6. 确定数据的分组间隔: 在构建直方图时,选择适当的分组间隔对于准确地反映数据分布至关重要

概念

组距:每组数据的分割区域,例如1-5一组5-10一组。我们可以称数据的组距为5

组数:(最大数据-最小数据)/组距 一般会100条数据可分5-12组

方法

hist(data,bins,density)

  • data 所有的数据

  • bins 分几组

  • density 显示概率

普通直方图

from matplotlib import pyplot as plt
from random import randint


plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False


# 1.准备数据
data = [randint(1, 100) for _ in range(100)]
# 2.绘制图表
plt.hist(data,20)

修改样式

# 1.准备数据
data = [randint(1, 100) for _ in range(100)]
# 2.绘制图表 修改样式
plt.hist(data,20,facecolor='tab:orange',edgecolor='white',alpha=0.5)

显示概率

# 1.准备数据
data = [randint(1, 100) for _ in range(100)]
# 2.绘制图表 修改样式
plt.hist(data,20,facecolor='tab:orange',edgecolor='white',alpha=0.5)

箱图(盒图)

SNAGHTML42f0361e

箱图(Box Plot),又称为箱形图、箱线图、盒式图、盒状图或盒须图,是一种用于展示数据分布情况的统计图表

箱图通过显示数据的中位数、上下四分位数(Q1和Q3)、异常值和数据的分布范围,提供了对数据整体特征的直观认识。以下是箱图的主要组成部分和特点:

image-20240110232737006

箱体(Box): 箱体代表数据集的四分位距,即上四分位数(Q3)和下四分位数(Q1)之间的区域。箱体的长度表示数据的分布范围,越长表示数据的变异性越大

中位数线(Median Line): 在箱体内部通常有一条横线,表示数据的中位数,即将数据集分为两半的位置

须(Whiskers): 须是延伸自箱体的线段,用于表示数据的整体范围。通常,须的长度限制在1.5倍的四分位距之内。超过这个范围的数据点被认为是潜在的异常值

异常值(Outliers): 箱图中的异常值是须之外的数据点,它们可能是数据中的极端值。异常值可以帮助识别数据中的离群观测

以下是箱图的一些主要用途和适用场景:

  1. 展示数据分布: 箱图可以清晰地展示数据集的整体分布情况,包括中位数、上下四分位数和异常值,提供了对数据分布形状的直观认识

  2. 观察中心位置和离散度: 通过箱图,可以轻松地识别数据的中位数和四分位数,帮助观察者了解数据的中心位置和变异性

  3. 检测异常值: 箱图有助于识别数据中的异常值,这些值可能是与数据集的整体分布不同的极端值

  4. 比较不同组别的数据分布: 箱图可以用于比较不同类别或组别的数据分布情况,从而观察它们之间的差异

  5. 评估对称性和偏斜: 箱图的形状有助于观察数据的对称性或偏斜,这对于了解数据的分布特征非常有用

  6. 用于统计分析和质量控制: 箱图常用于统计学分析和质量控制中,帮助决策者识别问题、制定策略和改进流程

方法

boxplot(data) 绘制盒图

单盒子

# 显示
data = [randint(1,100) for i in range(100)]
data.append(-60)
plt.boxplot(data)

多盒子

data = [randint(1,100) for i in range(100)]
data2 = [randint(1,100) for i in range(100)]
data.append(-60)
# vert=False 水平显示 默认是True
# notch=True 显示缺口
plt.boxplot([data,data2],notch=True,labels=['随机数','随机数2'],sym='yo')

散点图

image-20211227094656759

散点图是一种用于显示两个变量之间关系的图表,每个点代表数据集中的一个观测值。以下是散点图的主要作用和适用场景:

  1. 展示变量之间的关系: 散点图适用于展示两个变量之间的关系,帮助观察者了解它们之间的趋势、相关性或模式

  2. 识别趋势: 通过观察散点图中的点的分布,可以判断是否存在线性或非线性的趋势。这有助于理解变量之间的关联性

  3. 发现异常值: 散点图可以用于识别数据集中的异常值,即与其他数据点明显不同的观测值

  4. 比较不同群体或类别的关系: 如果数据可以按照不同的群体或类别划分,散点图可以用于比较这些群体或类别之间的变量关系

  5. 显示数据的分布: 在散点图中,密集的点集中通常表示较高的数据密度,反之表示较低的密度,从而有助于观察数据的分布情况

  6. 用于回归分析: 散点图是回归分析的重要工具,可以用于评估两个变量之间是否存在趋势,并用最佳拟合线(回归线)来描述这种趋势

方法

scatter(x,y) 绘制散点图

代码

from matplotlib import pyplot as plt


plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False


x = [161.2, 167.5, 159.5, 157.0, 155.8, 170.0, 159.1, 166.0, 176.2, 160.2, 172.5, 170.9, 172.9, 153.4, 160.0, 147.2, 168.2, 175.0, 157.0, 167.6, 159.5, 175.0, 166.8, 176.5, 170.2, 174.0, 173.0, 179.9, 170.5, 160.0, 154.4, 162.0, 176.5, 160.0, 152.0, 162.1, 170.0, 160.2, 161.3, 166.4, 168.9, 163.8, 167.6, 160.0, 161.3, 167.6, 165.1, 160.0, 170.0, 157.5, 167.6, 160.7, 163.2, 152.4, 157.5, 168.3, 180.3, 165.5, 165.0, 164.5, 156.0, 160.0, 163.0, 165.7, 161.0, 162.0, 166.0, 174.0, 172.7, 167.6, 151.1, 164.5, 163.5, 152.0, 169.0, 164.0, 161.2, 155.0, 170.0, 176.2, 170.0, 162.5, 170.3, 164.1, 169.5, 163.2, 154.5, 159.8, 173.2, 170.0, 161.4, 169.0, 166.2, 159.4, 162.5, 159.0, 162.8, 159.0, 179.8, 162.9, 161.0, 151.1, 168.2, 168.9, 173.2, 171.8, 178.0, 164.3, 163.0, 168.5, 166.8, 172.7, 163.5, 169.4, 167.8, 159.5, 167.6, 161.2, 160.0, 163.2, 162.2, 161.3, 149.5, 157.5, 163.2, 172.7, 155.0, 156.5, 164.0, 160.9, 162.8, 167.0, 160.0, 160.0, 168.9, 158.2, 156.0, 160.0, 167.1, 158.0, 167.6, 156.0, 162.1, 173.4, 159.8, 170.5, 159.2, 157.5, 161.3, 162.6, 160.0, 168.9, 165.1, 162.6, 165.1, 166.4, 160.0, 152.4, 170.2, 162.6, 170.2, 158.8, 172.7, 167.6, 162.6, 167.6, 156.2, 175.2, 172.1, 162.6, 160.0, 165.1, 182.9, 166.4, 165.1, 177.8, 165.1, 175.3, 154.9, 158.8, 172.7, 168.9, 161.3, 167.6, 165.1, 175.3, 157.5, 163.8, 167.6, 165.1, 165.1, 168.9, 162.6, 164.5, 176.5, 168.9, 175.3, 159.4, 160.0, 170.2, 162.6, 167.6, 162.6, 160.7, 160.0, 157.5, 162.6, 152.4, 170.2, 165.1, 172.7, 165.1, 170.2, 170.2, 170.2, 161.3, 167.6, 167.6, 165.1, 162.6, 152.4, 168.9, 170.2, 175.2, 175.2, 160.0, 165.1, 174.0, 170.2, 160.0, 167.6, 167.6, 167.6, 154.9, 162.6, 175.3, 171.4, 157.5, 165.1, 160.0, 174.0, 162.6, 174.0, 162.6, 161.3, 156.2, 149.9, 169.5, 160.0, 175.3, 169.5, 160.0, 172.7, 162.6, 157.5, 176.5, 164.4, 160.7, 174.0, 163.8]
y = [51.6, 59.0, 49.2, 63.0, 53.6, 59.0, 47.6, 69.8, 66.8, 75.2, 55.2, 54.2, 62.5, 42.0, 50.0, 49.8, 49.2, 73.2, 47.8, 68.8, 50.6, 82.5, 57.2, 87.8, 72.8, 54.5, 59.8, 67.3, 67.8, 47.0, 46.2, 55.0, 83.0, 54.4, 45.8, 53.6, 73.2, 52.1, 67.9, 56.6, 62.3, 58.5, 54.5, 50.2, 60.3, 58.3, 56.2, 50.2, 72.9, 59.8, 61.0, 69.1, 55.9, 46.5, 54.3, 54.8, 60.7, 60.0, 62.0, 60.3, 52.7, 74.3, 62.0, 73.1, 80.0, 54.7, 53.2, 75.7, 61.1, 55.7, 48.7, 52.3, 50.0, 59.3, 62.5, 55.7, 54.8, 45.9, 70.6, 67.2, 69.4, 58.2, 64.8, 71.6, 52.8, 59.8, 49.0, 50.0, 69.2, 55.9, 63.4, 58.2, 58.6, 45.7, 52.2, 48.6, 57.8, 55.6, 66.8, 59.4, 53.6, 73.2, 53.4, 69.0, 58.4, 56.2, 70.6, 59.8, 72.0, 65.2, 56.6, 105.2, 51.8, 63.4, 59.0, 47.6, 63.0, 55.2, 45.0, 54.0, 50.2, 60.2, 44.8, 58.8, 56.4, 62.0, 49.2, 67.2, 53.8, 54.4, 58.0, 59.8, 54.8, 43.2, 60.5, 46.4, 64.4, 48.8, 62.2, 55.5, 57.8, 54.6, 59.2, 52.7, 53.2, 64.5, 51.8, 56.0, 63.6, 63.2, 59.5, 56.8, 64.1, 50.0, 72.3, 55.0, 55.9, 60.4, 69.1, 84.5, 55.9, 55.5, 69.5, 76.4, 61.4, 65.9, 58.6, 66.8, 56.6, 58.6, 55.9, 59.1, 81.8, 70.7, 56.8, 60.0, 58.2, 72.7, 54.1, 49.1, 75.9, 55.0, 57.3, 55.0, 65.5, 65.5, 48.6, 58.6, 63.6, 55.2, 62.7, 56.6, 53.9, 63.2, 73.6, 62.0, 63.6, 53.2, 53.4, 55.0, 70.5, 54.5, 54.5, 55.9, 59.0, 63.6, 54.5, 47.3, 67.7, 80.9, 70.5, 60.9, 63.6, 54.5, 59.1, 70.5, 52.7, 62.7, 86.3, 66.4, 67.3, 63.0, 73.6, 62.3, 57.7, 55.4, 104.1, 55.5, 77.3, 80.5, 64.5, 72.3, 61.4, 58.2, 81.8, 63.6, 53.4, 54.5, 53.6, 60.0, 73.6, 61.4, 55.5, 63.6, 60.9, 60.0, 46.8, 57.3, 64.1, 63.6, 67.3, 75.5, 68.2, 61.4, 76.8, 71.8, 55.5, 48.6, 66.4, 67.3]
plt.scatter(x, y,color='tab:blue',alpha=0.5)
from matplotlib import pyplot as plt
from random import randint


plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False


x = []
y = [randint(1,100) for i in range(len(x))]
size = [i//10 for i in y]
color = [randint(1,100) for i in range(len(x))]
plt.scatter(x, y,c=color,s=y,alpha=0.5)

饼图

SNAGHTML42e8f732

饼图(Pie Chart)是一种常见的数据可视化图表,主要用于展示数据的相对比例。饼图通过将整体分割成扇形,每个扇形的角度大小表示相应类别的数据占总体的比例。以下是饼图的主要作用和适用场景:

  1. 显示相对比例: 饼图最主要的作用是显示不同类别或部分的数据在整体中所占的相对比例,通过扇形的大小直观地表达这些比例关系

  2. 强调部分与整体的关系: 饼图适用于突出各部分数据在整体中的比重,使观察者更容易理解每个类别对总体的贡献程度

  3. 用于少量类别的数据: 饼图通常适用于展示少量(2-7个)类别的数据,因为过多的扇形会使图表复杂难以解读

  4. 比较各类别的重要性: 饼图允许观察者直观比较各类别的相对重要性,即使这些类别的数值较小也能清晰呈现

方法

pie(data) 绘制饼图

常规饼图

labels = '鱼', '猫', '狗', '鹦鹉'
sizes = [15, 30, 45, 10]
plt.pie(data,labels=labels,autopct='%1.1f%%',colors=['tab:red','tab:blue','tab:green','tab:orange'])
plt.legend()

设置字体

labels = '鱼', '猫', '狗', '鹦鹉'
sizes = [15, 30, 45, 10]
plt.pie(data,labels=labels,autopct='%1.1f%%',
    textprops={'fontsize':20,'color':'tab:blue'})
plt.legend()

互换内容位置

labels = '鱼', '猫', '狗', '鹦鹉'
sizes = [15, 30, 45, 10]
plt.pie(data,labels=labels,
    pctdistance=1.2,  # 设置值距离圆心的距离
    labeldistance=0.6, # 设置标签距离圆心的距离
    autopct='%1.1f%%',colors=['tab:red','tab:blue','tab:green','tab:orange'])
plt.legend()

分离扇区

labels = '鱼', '猫', '狗', '鹦鹉'
sizes = [15, 30, 45, 10]


explode = (0, 0.1, 0.1, 0)
plt.pie(data,labels=labels,
    explode=explode, # 设置扇形的偏移量
    autopct='%1.1f%%',colors=['tab:red','tab:blue','tab:green','tab:orange'])
plt.legend(loc='best')

空心饼图

explode = (0, 0.1, 0.1, 0)
plt.pie(data,labels=labels,
    wedgeprops={'width':0.4},# 设置空心
    pctdistance=0.8, # 设置标签距离圆心的距离
    explode=explode, # 设置扇形的偏移量
    autopct='%1.1f%%',colors=['tab:red','tab:blue','tab:green','tab:orange'])
plt.legend(loc='best')

热力图

image-20240111162408453

热力图(Heatmap)是一种通过颜色编码来显示数据矩阵中各元素相对值的图表,它主要用于呈现数据的相对密度、强度或关联程度。以下是热力图的主要作用和适用场景:

  1. 显示数据矩阵的模式: 热力图适用于显示数据矩阵中各元素之间的相对关系,通过颜色的深浅反映元素的相对值大小

  2. 可视化关联程度: 热力图能够清晰地表达不同元素之间的关联程度,特别是在表示相关性矩阵或相似性矩阵时,颜色的变化可以直观地展示变量之间的相关性

  3. 观察趋势和模式: 热力图在时间序列分析中常用于观察数据的趋势和模式。时间和另一个维度的数据可以在热力图中以两个轴展示,颜色则表示数据的强度

  4. 聚类分析: 热力图可用于辅助聚类分析,帮助观察者识别数据集中的分组或模式,尤其是在生物学、金融和市场研究等领域

  5. 异常值检测: 通过热力图,可以识别数据中的异常值,因为异常值通常在热力图中表现为与其他元素不同颜色的点

  6. 地理信息可视化: 热力图可以用于可视化地理信息数据,如人口密度、温度分布等,通过颜色的变化呈现不同地区的相对值

  7. 可视化深度学习中的权重: 在深度学习中,热力图常被用于可视化神经网络的权重,以便更好地理解网络的学习过程

方法

imshow(data) 绘制热力图

常规热力图

days = [
  'Saturday', 'Friday', 'Thursday',
  'Wednesday', 'Tuesday', 'Monday', 'Sunday'
]
hours = [
  '12a', '1a', '2a', '3a', '4a', '5a', '6a',
  '7a', '8a', '9a', '10a', '11a',
  '12p', '1p', '2p', '3p', '4p', '5p',
  '6p', '7p', '8p', '9p', '10p', '11p'
]
data = [
   [5, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 1, 1, 3, 4, 6, 4, 4, 3, 3, 2, 5], 
   [7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 2, 2, 6, 9, 11, 6, 7, 8, 12, 5, 5, 7, 2], 
   [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 3, 2, 1, 9, 8, 10, 6, 5, 5, 5, 7, 4, 2, 4],
   [7, 3, 0, 0, 0, 0, 0, 0, 1, 0, 5, 4, 7, 14, 13, 12, 9, 5, 5, 10, 6, 4, 4, 1], 
   [1, 3, 0, 0, 0, 1, 0, 0, 0, 2, 4, 4, 2, 4, 4, 14, 12, 1, 8, 5, 3, 7, 3, 0], 
   [2, 1, 0, 3, 0, 0, 0, 0, 2, 0, 4, 1, 5, 10, 5, 7, 11, 6, 0, 5, 3, 4, 2, 0], 
   [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 2, 1, 3, 4, 0, 0, 0, 0, 1, 2, 2, 6]
]
# 绘制热力图
plt.imshow(data)

带样式

# 创建画布
plt.figure(figsize=(20,10))
# 绘制热力图
plt.imshow(data,cmap='rainbow')
# 设置x轴刻度
plt.xticks(range(24),hours)
# 设置y轴刻度
plt.yticks(range(7),days)
# 显示颜色条
plt.colorbar()
# 显示数值
for i,d in enumerate(data):
  for j,h in enumerate(d):
    plt.text(j,i,data[i][j],ha='center',va='center',color='w')

3D图表

image-20240111190424716

设置画布为3D

# 绘制图形
fig = plt.figure()
ax = fig.add_subplot(projection='3d')

3D折线图

# 绘制3D折线图
# 准备数据
x = [1, 2, 3, 4, 5, 6, 7]
y = [3, 5, 6, 15, 17, 18, 2]
z = [1, 2, 3, 4, 5, 6, 7]


# 绘制图形
fig = plt.figure()
ax = fig.add_subplot(projection='3d')
plt.plot(x, y, z)

3D散点图

x = [randint(1,20) for i in range(100)]
y = [randint(1,20) for i in range(100)]
z = [randint(1,20) for i in range(100)]
# 绘制图形
fig = plt.figure()
ax = fig.add_subplot(projection='3d')
plt.scatter(x, y, z, color='tab:red', marker='*')

3D条图

x = range(3)


# 绘制条图
fig = plt.figure()
ax = fig.add_subplot(projection='3d')
colors = ['tab:red', 'tab:blue', 'tab:green']


for i in x:
  y = [randint(1,20) for i in range(6)]
  z = [randint(5,20) for i in range(6)]
  plt.bar(y, z, zs=i,zdir='x', alpha=0.8,width=1.8,color=[colors[i] for _ in range(6)])
  plt.xticks(range(0,3,1))
  ax.set_xlabel('x轴')
  ax.set_ylabel('y轴')
  ax.set_zlabel('z轴')
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值