Matplotlib Pyplot
Pyplot 是 Matplotlib 的子库,提供了和 MATLAB 类似的绘图 API。
使用的时候,我们可以使用 import 导入 pyplot 库,并设置一个别名 plt:
import matplotlib.pyplot as plt
这样我们就可以使用 plt 来引用 Pyplot 包的方法。以下是一些常用的 pyplot 函数:
plot():用于绘制线图和散点图
scatter():用于绘制散点图
bar():用于绘制垂直条形图和水平条形图
hist():用于绘制直方图
pie():用于绘制饼图
imshow():用于绘制图像
subplots():用于创建子图,例如 plt.subplot(235) 将绘图区域划分为 2 行 3 列,并在第 5 个位置创建子图
添加标签和标题
plt.xlabel('Product')
plt.ylabel('Total Sales')
plt.title('Stacked Sales by Product and Year')
绝大多数的 plt 函数都可以直接转换成 axes 方法(例如 plt.plot() → axes.plot()、plt.legend() → axes.legend() 等)。
图例 (Legend)
plt.legend() 创建图例。
loc:图例位置,如 "best"(默认)、"upper right"、"lower left" 等。
fontsize:字体大小,可为数值或 'small'、'large' 等关键字。
title:图例标题,可配合 title_fontsize 调整大小。
ncol:列数,适合多系列数据时分列显示。
刻度与文本
plt.xticks(位置,标签) 设置 x 轴刻度。例子:plt.xticks([0,1.5,3,4.5], df2.index)。
plt.text() 函数用于设置文字说明。在图表中添加文本:
plt.text(x, y, string, fontsize=15, verticalalignment="top", horizontalalignment="right")
x, y:表示坐标值上的值
string:文字
fontsize:表示字体大小
va:垂直对齐方式,参数:['center', 'top', 'bottom', 'baseline']
ha:水平对齐方式,参数:['center', 'right', 'left']
举例:plt.text(x + 0.4, -y - 0.05, '%.2f' % y, ha='center', va='top')
子图示例
import matplotlib.pyplot as plt
plt.figure(figsize=(13,9))
plt.rcParams['font.family']='SimHei'
plt.subplot(231)
x=['a','b','c']
hight=[1,3,2]
a=plt.bar(x,hight)
print(vars(a))
plt.title('默认')
plt.subplot(232)
x=['a','b','c']
hight=3
width=0.2
plt.bar(x,hight,width)
plt.title('hight=3、width=0.2')
plt.subplot(233)
x=['a','b','c']
width=[0.3,0.2,0.4]
hight=[1,3,2]
a=plt.bar(x,hight,width)
plt.title('width=[0.3,0.2,0.4]')
plt.subplot(234)
x=['a','b','c']
hight=[1,3,2]
width=0.2
bottom=0.2
plt.ylim(0,4)
plt.bar(x,hight,width,bottom)
plt.title('bottom=0.2、plt.ylim(0,4)')
plt.subplot()
x=[,,]
hight=[,,]
plt.bar(x,hight,align=)
plt.title()
plt.subplot()
x=[,,]
hight=[,,]
width=-
plt.bar(x,hight,width,align=)
plt.title()
plt.show()
plot() 函数
plot() 函数是绘制二维图形的最基本函数。
plt.plot(x, y, fmt,**kwargs)
x:表示 X 轴上的数据点,通常是一个列表、数组或一维序列。
y:表示 Y 轴上的数据点,通常也是一个列表、数组或一维序列。
fmt:可选的格式字符串,用于指定线条的样式、标记和颜色。例如,'ro-' 表示红色圆点线条。
**kwargs:一系列可选参数,用于进一步自定义线条的属性,如线宽、标记大小、标签等。
常用参数和用法:
- 样式参数(fmt):格式字符串可以包含一个字符来指定颜色,一个字符来指定标记样式,以及一个字符来指定线条样式。例如,'r-' 表示红色实线,'bo--' 表示蓝色圆点虚线。
- 线条样式(linestyle):使用 linestyle 参数可以指定线条的样式,如实线('-')、虚线('--')、点划线('-.')等。
- 标记样式(marker):使用 marker 参数可以指定数据点的标记样式,如圆点('o')、方块('s')、星号('*')等。
- 线条颜色(color):使用 color 参数可以指定线条的颜色,可以使用颜色名称(如'red')、缩写(如'r')或十六进制颜色码(如'#FF5733')。
- 线宽(linewidth):使用 linewidth 参数可以指定线条的宽度,以数字表示。
bar 柱状图
matplotlib.pyplot.bar(x, height, width=0.8, bottom=None,*, align='center', data=None,**kwargs)
bar() 的返回值为 BarContainer 对象,其中 patche 属性为 Rectangle 列表,即一系列柱子。
基础参数如下:
x:柱子在 x 轴上的坐标。浮点数或类数组结构。注意 x 可以为字符串数组!
height:柱子的高度,即 y 轴上的坐标。浮点数或类数组结构。
width:柱子的宽度。浮点数或类数组结构。默认值为 0.8。
bottom:柱子的基准高度。浮点数或类数组结构。默认值为 0。
align:柱子在 x 轴上的对齐方式。字符串,取值范围为 {'center', 'edge'},默认为 'center'。
- 'center':x 位于柱子的中心位置。
- 'edge':x 位于柱子的左侧。如果想让 x 位于柱子右侧,需要同时设置负 width 以及 align='edge'。
柱子的位置由 x 以及 align 确定,柱子的尺寸由 height 和 width 确定。垂直基准位置由 bottom 确定 (默认值为 0)。大部分参数既可以是单独的浮点值也可以是值序列,单独值对所有柱子生效,值序列一一对应每个柱子。
数据准备与转置
import pandas as pd
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif']=['SimHei']
plt.rcParams['axes.unicode_minus']=False
data ={'python 基础':[86,99,68,83,79,91],'数据结构':[78,66,58,75,77,59],'数据分析':[68,99,68,83,79,91]}
df= pd.DataFrame(data,index=['杨东','李力','王雷','赵平','张也','张三'])
rows = df.index
rows_value = rows.values
print(rows)
print(rows_value)
columns = df.columns
print(columns)
print(columns.values)
转置
df2=pd.DataFrame(df.values.T,index=df.columns,columns=df.index)
折线图示例
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif']=['SimHei']
x =[1,2,3,4,5]
y =[10,15,13,18,16]
plt.figure(figsize=(3,3))
plt.plot(
x,
y,
marker='o',
linestyle='-',
color='green',
linewidth=2,
markersize=10,
label='数据 1'
)
plt.xlabel('X 轴标签')
plt.ylabel('Y 轴标签')
plt.title('标题')
plt.legend()
plt.grid(True)
plt.xticks([1,2,3,4,5],['一','二','三','四','五'])
plt.show()
柱状图变体
立柱
使用 plt.bar(x,y)。
卧倒柱
使用 plt.barh(x,y),height 与 width 含义互换。
多个柱
同一 x 轴位置绘制多个柱状图,主要通过调整柱状图的宽度和每个柱状图 x 轴的起始位置。
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
plt.style.use('seaborn-v0_8')
plt.rcParams['font.sans-serif']=['SimHei']
plt.rcParams['axes.unicode_minus']=False
plt.figure(figsize=(12,6))
bar_width =0.25
r1 = np.arange(3)
r2 = [x + bar_width for x in r1]
r3 = [x + bar_width for x in r2]
plt.figure(figsize=(3,3))
bar_width =0.25
r1 =range(3)
r2 = [x + bar_width for x in r1]
r3 = [x + bar_width for x in r2]
plt.bar(r1, df2.iloc[:,0], color='blue', width=bar_width, label='杨东')
plt.bar(r2, df2.iloc[:,1], color='green', width=bar_width, label='李力')
plt.bar(r3, df2.iloc[:,2], color='purple', width=bar_width, label='王雷')
plt.xlabel('成绩')
plt.ylabel('课程')
plt.title('3 人在 3 门课的成绩')
plt.xticks([r + bar_width for r in ()], df2.index)
plt.legend()
设置柱子位置的另一种方式
plt.figure(figsize=(3,3))
plt.bar(r1-bar_width, df2.iloc[:,0], color='blue', width=bar_width, label='杨东')
plt.bar(r1, df2.iloc[:,1], color='green', width=bar_width, label='李力')
plt.bar(r1+bar_width, df2.iloc[:,2], color='purple', width=bar_width, label='王雷')
绘制 6 人三科目
需要提前计算好整个 x 轴的长度,每个柱所在位置。
import pandas as pd
import matplotlib.pyplot as plt
plt.style.use('seaborn-v0_8')
plt.rcParams['font.sans-serif']=['SimHei']
plt.rcParams['axes.unicode_minus']=False
plt.figure(figsize=(7,3))
bar_width =0.25
r1 = [0,1.75,3.5]
r2 = [x + bar_width for x in r1]
r3 = [x + bar_width for x in r2]
r4 = [x + bar_width for x in r3]
r5 = [x + bar_width for x in r4]
r6 = [x + bar_width for x in r5]
bars1=plt.bar(r1, df2.iloc[:,0], color='blue', width=bar_width, label='杨东',alpha=0.8, edgecolor='white')
bars2=plt.bar(r2, df2.iloc[:,1], color='green', width=bar_width, label='李力',alpha=0.8, edgecolor='white')
bars3=plt.bar(r3, df2.iloc[:,2], color='purple', width=bar_width, label='王雷',alpha=0.8, edgecolor='white')
bars4=plt.bar(r4, df2.iloc[:,3], color='yellow', width=bar_width, label='赵平',alpha=0.8, edgecolor='white')
bars5=plt.bar(r5, df2.iloc[:,4], color='pink', width=bar_width, label=,alpha=, edgecolor=)
bars6=plt.bar(r6, df2.iloc[:,], color=, width=bar_width, label=,alpha=, edgecolor=)
():
bar bars:
height = bar.get_height()
plt.text(bar.get_x()+ bar.get_width()/, height,
, ha=, va=)
add_labels(bars1)
add_labels(bars2)
add_labels(bars3)
add_labels(bars4)
add_labels(bars5)
add_labels(bars6)
plt.xlabel()
plt.ylabel()
plt.title(,fontweight=)
plt.xticks([r +*bar_width r [,,]], df2.index)
plt.legend(loc=, frameon=)
plt.grid(axis=, linestyle=, alpha=)
plt.tight_layout()
plt.show()
堆积柱
bottom 参数来指定每一层的起始位置。
plt.figure(figsize=(5,5))
plt.bar(df2.index,df2['杨东'],width=0.25)
plt.bar(df2.index,df2['李力'],width=0.25,bottom=df2['杨东'])
plt.bar(df2.index,df2['王雷'],width=0.25,bottom=df2['杨东']+df2['李力'])
双向柱
上下双向柱
下方柱值乘(-1)。
plt.figure(figsize=(3,3))
b1=plt.bar(df2.index,df2['杨东'],width=0.25)
b2=plt.bar(df2.index,-df2['张三'],width=0.25)
def add_labels(bars):
for bar in bars:
height = bar.get_height()
plt.text(bar.get_x()+ bar.get_width()/2., height,
f'{height}', ha='center', va='bottom')
add_labels(b1)
add_labels(b2)
plt.legend(['杨东','张三'],loc='best')
左右双向柱
主要在于 barh 的使用,以及左边柱要乘(-1)。
plt.figure(figsize=(5,3))
b1=plt.barh(df2.index,df2['杨东'],height=0.25)
b2=plt.barh(df2.index,-df2['张三'],height=0.25)
def add_labels(bars):
for bar in bars:
width = bar.get_width()
plt.text(width, bar.get_y()+ bar.get_height()/2.,
f'{width}', ha='center', va='bottom')
add_labels(b1)
add_labels(b2)
plt.legend(['杨东','张三'],loc='best')