Matplotlib
1. pylab模块
是Matplotlib的一个模块,可以直接使用numpy函数和matplotlib.pylot的绘图功能
语法:
import matplotlib.pyplot as plt
import numpy as np
2. plot函数
根据提供的x,y绘图。
pylab.plot(x, y, format_string=None, **kwargs)
参数:
- x:x轴数据
- y:y轴数据
- format_string:格式化字符串,用于指定线条样式、颜色等。
- **kwargs:其他关键字参数,用来指定线条其他属性。
def mat_plot():
x = np.linspace(-10,10,100)
y = 1/(x**2-4)
#plot:根据x,y值画出曲线
plt.plot(x,y)
#show():显示图片
plt.show()
mat_plot()
3. figure函数
figure() 函数来实例化 figure 对象,即绘制图形的对象,可以通过这个对象,来设置图形的样式等
参数:
- figsize:指定画布的大小,(宽度,高度),单位为英寸
- dpi:指定绘图对象的分辨率,即每英寸多少个像素,默认值为80
- facecolor:背景颜色
- dgecolor:边框颜色
- frameon:是否显示边框
def mat_figure():
生成画布,figsize是设置画布的高度和宽度(单位是英寸)
fig = plt.figure(figsize=(12,4))
#在画布上生成区域
ax = fig.add_axes([0.1,0.1,0.8,0.8])
x = np.linspace(-10,10,10)
y = x**2
#根据x,y生成曲线并展示
line1 = ax.plot(x,y,label='s^2')
# ax.legend(handles=line1,labels=['x^2'],loc='upper left')
# plt.show()
y1 = np.sin(x)
line2 = ax.plot(x,y1,label='sin(x)')
#legend:图像设置
#handles:包含曲线对象,如果有一个对象直接将该对象赋值给handles,如果有多个对象则使用列表赋值
#labels:设置图例显示的内容,值是一个列表
#loc: 设置图像显示位置
# ax.legend(handles=line2, labels=['sin(x)'], loc='upper left')
ax.legend()
ax.set_title('你好')
plt.show()
mat_figure()
4. 标题中文乱码
局部处理:
plt.rcParams['font.sans-serif']=['SimHei']
plt.rcParams['axes.unicode_minus']=False
全局处理:
首先,找到 matplotlibrc
文件的位置,可以使用以下代码:
import matplotlib
print(matplotlib.matplotlib_fname())
然后,修改 matplotlibrc
文件,找到 font.family
和 font.sans-serif
项,设置为支持中文的字体,如 SimHei。
同时,设置 axes.unicode_minus
为 False
以正常显示负号。
修改完成后,重启pyCharm。如果不能解决,尝试运行以下代码来实现:
from matplotlib.font_manager import _rebuild
_rebuild()
5.subplot函数
用于创建并返回一个子图对象。参数通常为一个三组整数,分别代表子图的行数,列数和子图索引。
fig.add_subplot(nrows, ncols, index)
#add_subplot:在画布中添加子绘图区域
#rows:绘图区域行数
#cols:绘图区域列数
#index:占绘图区域的编号
def mat_subplot():
x = np.linspace(0,10,100)
y1 = np.sin(x)
y2 = np.cos(x)
y3 = np.tan(x)
fig = plt.figure(figsize=(12,4))
ax1 = fig.add_subplot(1,3,1)
ax1.plot(x,y1,label='sin(x)')
ax1.legend()
ax2 = fig.add_subplot(132)
ax2.plot(x,y2,label='cos(x)')
ax2.legend()
ax3 = fig.add_subplot(133)
ax3.plot(x,y3,label='tan(x)')
ax3.legend()
plt.tight_layout()
plt.show()
mat_subplot()
6. subplots函数
用于创建一个包含多个子图的图形窗口。
fig, axs = plt.subplots(nrows, ncols, figsize=(width, height))
参数:
- nrows: 子图的行数。
- ncols: 子图的列数。
- figsize: 图形的尺寸,以英寸为单位。
def mat_subplots():
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)
y3 = np.tan(x)
fig,axs = plt.subplots(2,2,figsize=(12,8))
axs[0,0].plot(x,y1,label='sin(x)')
axs[0,0].legend()
axs[0,1].plot(x,y2,label='cos(x)')
axs[0,1].legend()
axs[1,0].plot(x,y3,label='tan(x)')
axs[1,0].legend()
plt.show()
mat_subplots()
7. subplotgird函数
用于在网格中创建子图,可以更灵活的指定子图的位置和大小,以非等分的形式对画布进行切分,可以创建复杂的布局。
ax = plt.subplot2grid(shape, loc, rowspan=1, colspan=1)
参数:
- shape: 网格的形状,格式为 (rows, cols),表示网格的行数和列数,在figure中是全局设置。
- loc: 子图的起始位置,格式为 (row, col),表示子图在网格中的起始行和列。
- rowspan: 子图占据的行数,默认为 1。
- colspan: 子图占据的列数,默认为 1。
def mat_subplot2gird():
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)
y3 = np.tan(x)
y4 = np.arcsin(x)
ax1 = plt.subplot2grid((3,3),(0,0))
ax1.plot(x,y1,label='sin(x)')
ax1.set_xlim(0,2*np.pi)
ax2 = plt.subplot2grid((3,3),(0,1))
ax2.plot(x,y2,label='cos(x)')
ax3 = plt.subplot2grid((2,2),(1,0))
ax3.plot(x,y3,label='tan(x)')
ax3.grid(True,which='both',axis='both')
ax3.set_xscale('log')
ax3.set_yscale('log')
ax4 = plt.subplot2grid((2,2),(1,1))
ax4.plot(x,y4,label='arcsin(x)')
# plt.tight_layout()
plt.show()
mat_subplot2gird()
#grid函数:grid 是用于在图形中添加网格线的函数。
#xscale/ysclae函数:xscale 和 yscale 函数用于设置坐标轴的刻度类型。
#set_xlim 和 set_ylim 函数用于设置坐标轴的范围。
8. set_xticks 和 set_yticks 函数
Matplotlib 可以自动根据因变量和自变量设置坐标轴范围,也可以通过 set_xticks() 和 set_yticks() 函数手动指定刻度,接收一个列表对象作为参数,列表中的元素表示对应数轴上要显示的刻度。
def mat_ticks():
x = np.linspace(0,10,100)
y = np.sin(x)
fig,ax = plt.subplots()
ax.plot(x,y,label='sin(x)')
ax.set_xticks([0,2,4,6,8,10])
ax.set_yticks([-1,-0.5,0,0.5,1])
plt.show()
mat_ticks()
9. twinx和twiny函数
twinx 和 twiny 函数用于在同一个图形中创建共享 X 轴或 Y 轴的多个子图。
#twinx:两个子图曲线共用x轴
#twiny:两个子图曲线共用y轴
def mat_twin():
x = np.linspace(0,10,100)
y1 = np.sin(x)
y2 = np.cos(x)
fig,ax1 = plt.subplots()
ax1.plot(x,y1,label='sin(x)')
ax2 = ax1.twinx()
ax2.plot(x,y2,'r')
plt.show()
mat_twin()
10. 柱状图
语法:
ax.bar(x, height, width=0.8, bottom=None, align='center', **kwargs)
参数:
- x: 柱状图的 X 轴位置。
- height: 柱状图的高度。
- width: 柱状图的宽度,默认为 0.8。
- bottom: 柱状图的底部位置,默认为 0。
- align: 柱状图的对齐方式,可以是 ‘center’(居中对齐)或 ‘edge’(边缘对齐)。
- **kwargs: 其他可选参数,用于定制柱状图的外观,如 color、edgecolor、linewidth 等。
#bar:柱状图
#bottom:柱状图的底部位置,可以通过该属性实现堆叠珠状图:第二个柱状图的底部设置在第一个柱状图的高度上
def mat_bar():
x = ['A','B','C','D']
y = [20,30,15,40]
y2 = [10,40,10,35]
fig,ax = plt.subplots()
ax.bar(x,y,width=0.5,align='center',color='y',label='y')
ax.bar(x,y2,bottom=y,width=0.5,color='red',label='y2')
plt.show()
mat_bar()
def mat_bar1():
x = ['A', 'B', 'C', 'D']
y = [20,30,15,40]
y2 = [10, 40, 10, 35]
fig,ax = plt.subplots()
x1 = np.arange(len(x))
width = 0.2
ax.bar(x1-width/2,y,width,color='r')
ax.bar(x1+width/2,y2,width,color='b')
plt.show()
mat_bar1()
11. 直方图
语法:
ax.hist(x, bins=None, range=None, density=False, weights=None, cumulative=False, **kwargs)
参数:
- x: 数据数组。
- bins: 直方图的柱数,可以是整数或序列。
- range: 直方图的范围,格式为
(min, max)
。 - density: 是否将直方图归一化,默认为
False
。 - weights: 每个数据点的权重。
- cumulative: 是否绘制累积直方图,默认为
False
。 - **kwargs: 其他可选参数,用于定制直方图的外观,如
color
、edgecolor
、linewidth
等。
def mat_hist():
x = np.random.randn(1000)
fig,ax = plt.subplots()
ax.hist(x,bins=30,edgecolor='y')
plt.show()
mat_hist()
12. 饼图
语法:
ax.pie(x, explode=None, labels=None, colors=None, autopct=None, shadow=False, startangle=0, **kwargs)
参数:
- x: 数据数组,表示每个扇区的占比。
- explode: 一个数组,表示每个扇区偏离圆心的距离,默认为
None
。 - labels: 每个扇区的标签,默认为
None
。 - colors: 每个扇区的颜色,默认为
None
。 - autopct: 控制显示每个扇区的占比,可以是格式化字符串或函数,默认为
None
。 - shadow: 是否显示阴影,默认为
False
。 - startangle: 饼图的起始角度,默认为 0。
- **kwargs: 其他可选参数,用于定制饼图的外观。
def mat_pie():
x = ['A','B','C','D']
y = [10,20,35,15]
fif,ax = plt.subplots()
ax.pie(y,labels=x,startangle=90,autopct='%1.2f%%')
plt.show()
mat_pie()