其他分享
首页 > 其他分享> > Matplotlib打卡3

Matplotlib打卡3

作者:互联网

第三回:布局格式定方圆

资料参考:
matplotlib官网
Datawhale学习资料

import numpy as  np
import pandas as pd
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei'] # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False # 用来正常显示负号

一、 子图

使用plt.subplots绘制均匀状态下的子图

返回元素分别是画布和子图构成的列表,第一个数字为行,第二个为列

figsize 参数可以指定整个画布的大小

sharexsharey 分别表示是否共享横轴和纵轴刻度

tight_layout 函数可以调整子图的相对大小使字符不会重叠

fig,axs = plt.subplots(2,5,figsize=(10,4),sharex=True,sharey=True) # 2行,5列,共享x轴和y轴
fig.suptitle('样例1',size=20)  # 这里是共享的大标题
for i in range(2):
    for j in range(5):
        axs[i][j].scatter(np.random.randn(10),np.random.randn(10))
        axs[i][j].set_title("第%d行,第%d列"%(i+1,j+1))  #  这种循环绘制多个子图的方法好棒!
        axs[i][j].set_xlim(-5,5)
        axs[i][j].set_ylim(-5,5)
        if i==1:
            axs[i][j].set_xlabel('横坐标') # 共享横坐标,只给最下面一行设置set_xlabel
        if j==0: 
            axs[i][j].set_ylabel('纵坐标') # 共享纵坐标,只给最左侧一列设置set_ylabel

# 如果不加这一句,会出现大标题和图重叠的问题
fig.tight_layout() # 调整子图的相对大小使字符不会重叠

在这里插入图片描述

上面的例子fig,axs = plt.subplots(2,5) 绘制多个子图

然后使用axs[i][j]的方式设置每个子图的属性,

调用set_xlim(),set_xlabel(),set_title()等方法

除了常规的直角坐标系,也可以通过projection方法创建极坐标系下的图表

# 第一次用python画极坐标下的图表
N = 150
r = 2*np.random.rand(N) # 均匀分布的随机数
theta = 2*np.pi*np.random.rand(N)
area = 200 * r**2 # 200r的平方
colors = theta

plt.subplot(121,projection='polar')#projection = 'polar' 指定为极坐标
plt.scatter(theta,r,c=colors,s=area,cmap='hsv',alpha=0.75) 
#plt.scatter(theta,r,c=colors,cmap='hsv',alpha=0.75) 
# s = area是每个散点的大小,注释掉散点的大小会一样

# #第一个参数为角度,第二个参数为极径
plt.subplot(122,projection='polar')#projection = 'polar' 指定为极坐标
r = np.arange(0,1,0.001)
theta = 2*2*np.pi*r
plt.scatter(theta,r,linewidth=1,color='red',alpha=0.75)  # 传入每个点对应的角度和半径

plt.show()

在这里插入图片描述

2.使用GridSpec绘制非均匀子图

所谓非均匀包含两层含义,第一是指图的比例大小不同但没有跨行或跨列,第二是指图为跨列或跨行状态

利用 add_gridspec 可以指定相对宽度比例 width_ratios 和相对高度比例参数 height_ratios

fig = plt.figure(figsize=(10, 4))
spec = fig.add_gridspec(nrows=2, ncols=5, width_ratios=[1,2,3,4,5], height_ratios=[1,3])
# 2行5列。每行5子图,这五个子图的宽度比是1:2:3:4:5;每列2个图,他们的高度比是1:3
fig.suptitle('样例2', size=20)# 设置共同的大标题
for i in range(2):
    for j in range(5):
        ax = fig.add_subplot(spec[i, j]) # 在fig上加子图
        ax.scatter(np.random.randn(10), np.random.randn(10))
        ax.set_title('第%d行,第%d列'%(i+1,j+1))
        if i==1: 
            ax.set_xlabel('横坐标')
        if j==0: 
            ax.set_ylabel('纵坐标')
fig.tight_layout() # 避免字符重叠

在这里插入图片描述

在上面的例子中出现了 spec[i, j] 的用法,事实上通过切片就可以实现子图的合并而达到跨图的功能

fig = plt.figure(figsize=(10, 4))
spec = fig.add_gridspec(nrows=2, ncols=6, width_ratios=[2,2.5,3,1,1.5,2], height_ratios=[1,2])
fig.suptitle('样例3', size=20)
# sub1
ax = fig.add_subplot(spec[0, :3]) # 第一行的前三个图合并,然后这位置用来画新的图
ax.scatter(np.random.randn(10), np.random.randn(10))
# sub2
ax = fig.add_subplot(spec[0, 3:5])# 第一行的三四图合并,在这位置画新图
ax.scatter(np.random.randn(10), np.random.randn(10))
# sub3
ax = fig.add_subplot(spec[:, 5]) # 第五列的两幅子图合并画一个新图
ax.scatter(np.random.randn(10), np.random.randn(10))
# sub4
ax = fig.add_subplot(spec[1, 0]) # 第二行的第一图
ax.scatter(np.random.randn(10), np.random.randn(10))
# sub5
ax = fig.add_subplot(spec[1, 1:5]) # 第二行的后4图
ax.scatter(np.random.randn(10), np.random.randn(10))

# 没有这句,会发现坐标轴有重合
fig.tight_layout()

在这里插入图片描述

二、子图上的方法

在ax对象上定义了和plt类似的图形绘制函数,常用的有:plot,hist, scatter, bar, barh, pie
fig, ax = plt.subplots(figsize=(4,3))
ax.plot([1,2],[2,1]);

在这里插入图片描述

fig, ax = plt.subplots(figsize=(4,3))
ax.hist(np.random.randn(1000));

在这里插入图片描述

常用直线的画法为: axhline, axvline, axline (水平、垂直、任意方向)
fig, ax = plt.subplots(figsize=(4,3))
ax.axhline(0.5,0.2,0.8) # 三个参数分别是 (y值,x最小值、x最大值)
ax.axvline(0.5,0.2,0.8)# 三个参数分别是 (x值,y最小值、y最大值)
ax.axline([0.3,0.3],[0.7,0.7]); # 直线中两个点的横纵坐标

在这里插入图片描述

使用 grid 可以加灰色网格
fig, ax = plt.subplots(figsize=(4,3))
ax.grid(True)

在这里插入图片描述

使用 set_xscale, set_title, set_xlabel 分别可以设置坐标轴的规度(指对数坐标等)、标题、轴名
fig, axs = plt.subplots(1, 2, figsize=(10, 4))
fig.suptitle('大标题', size=20)
for j in range(2):
    axs[j].plot(list('abcd'), [10**i for i in range(4)]) # 用一个list设置横坐标的的值
    if j==0:
        axs[j].set_yscale('log') # 对数
        axs[j].set_title('子标题1')
        axs[j].set_ylabel('对数坐标')
    else:
        axs[j].set_title('子标题1')
        axs[j].set_ylabel('普通坐标')
fig.tight_layout()

在这里插入图片描述

与一般的 plt 方法类似, legend, annotate, arrow, text 对象也可以进行相应的绘制
fig, ax = plt.subplots()
ax.arrow(-0.5, -0.5, 1, 1, head_width=0.03, head_length=0.05, facecolor='red', edgecolor='blue')
# 前四个参数(x,y,dx,dy) 所以画的arrow的起始点为(x,y)终止点为(x+dy,x+dy) 
ax.text(x=0, y=0,s='这是一段文字', fontsize=16, rotation=70, rotation_mode='anchor', color='green')
# ax.text(x,y,s) 分别是放text的位置的横纵坐标以及要放的字符串  rotation_mode=‘anchor’是先对齐再旋转,与“default”结果有一点区别
ax.annotate('这是中点', xy=(0.5, 0.5), xytext=(0.8, 0.2), arrowprops=dict(facecolor='yellow', edgecolor='black'), fontsize=16);

在这里插入图片描述

设置图例的位置
fig, ax = plt.subplots()
ax.plot([1,2],[2,1],label="line1") # 图例
ax.plot([1,1],[1,2],label="line1")
ax.legend(loc=1);  
# 0->best,1--->upper right,2---->upper left,3--->lower left
# 4--->lower right,5-->right,6--->center left,7--->center right
#8--->lower center # 9--->upper center # 10-->center

在这里插入图片描述

标签:10,plt,Matplotlib,set,fig,np,ax,打卡
来源: https://blog.csdn.net/weixin_43803950/article/details/122056449