【Matplotlib学习笔记】Part3:布局

这篇博客展示了如何使用Python的matplotlib库进行数据可视化,包括极坐标下的玫瑰图、多子图的绘制以及非均匀子图的布局。实例涵盖了时间序列数据的处理、散点图、柱状图和直方图的绘制,以及子图的共享轴和调整。内容涵盖了数据预处理、图形布局和定制等关键步骤。
摘要由CSDN通过智能技术生成

Part3:布局

练习题:在极坐标下绘制玫瑰图
# 获取数据
ex1 = pd.read_csv('layout_ex1.csv')
data=ex1[0:12]

# 计算角度
n=data.shape[0]
print(n)
theta=np.linspace(0, np.pi*2, len(r), endpoint=False)      # 360度等分成n份

# 设置画布
fig = plt.figure(figsize=(12,10))
r=data['Temperature'].tolist()
# 极坐标
ax = plt.subplot(111,projection = 'polar')
# 顺时针并设置N方向为0度
ax.set_theta_direction(-1)
ax.set_theta_zero_location('N') 

# 在极坐标中画柱形图
ax.bar(theta,r,width=2*np.pi/n,color=np.random.random((n,3)),align="edge" )

#显示一些简单的中文图例
plt.rcParams['font.sans-serif']=['SimHei']  # 黑体
ax.set_title('墨尔本81年逐月温度',fontdict={'fontsize':20})
for angle,t,time in zip(theta,r,data['Time'].to_list()):
    ax.text(angle+0.03,t,str(time) )

在这里插入图片描述

思考题
1.墨尔本1981年至1990年的每月温度情况
data = pd.read_csv('layout_ex1.csv')
data['year']=pd.to_datetime(data['Time']).dt.year
data['month']=pd.to_datetime(data['Time']).dt.month
years=data.groupby(['year'])
month=list(range(1,13))

fig, axs = plt.subplots(2, 5, figsize=(10, 4), sharex=True, sharey=True)
fig.suptitle('墨尔本1981年至1990年的每月温度情况', size=20)
x=0
for year,tem in years:
    i=x // 5
    j=x % 5
    temp=pd.DataFrame(tem)
    axs[i][j].plot(month,temp['Temperature'].to_list(),marker='*')
    axs[i][j].set_title(f'{year}年')
    axs[i][j].set_xlim(0,13)
    axs[i][j].set_ylim(0,30)
    if i==1: axs[i][j].set_xlabel('month')
    if j==0: axs[i][j].set_ylabel('temperature')
    x+=1
fig.tight_layout()
#fig.tight_layout(rect=[0, 0, 1, 0.95]) #用以解决figure标题重叠问题,前面四个参数可根据具体情况做适当修改
#plt.subplots_adjust(top=0.85) #看下面两幅图就可以看出参数0.85的意义;
plt.subplots_adjust(top=0.8)

在这里插入图片描述

2.用 np.random.randn(2, 150) 生成一组二维数据,使用两种非均匀子图的分割方法,做出该数据对应的散点图和边际分布图
data=np.random.randn(2, 150)

fig = plt.figure(figsize=(10,10))
spec = fig.add_gridspec(nrows=2,ncols=2,width_ratios=[3,1],height_ratios=[1,3])

# 1
ax = fig.add_subplot(spec[1,0])
ax.grid(True)
ax.scatter(data[0,:],data[1,:])

# 2
ax = fig.add_subplot(spec[0,0])
ax.hist(data[0,:])
ax.axis('off')

# 3
ax = fig.add_subplot(spec[1,1])
ax.hist(data[1,:],orientation='horizontal')
ax.axis('off')

plt.subplots_adjust(wspace=0.025,hspace=0.025) #调整子图间距

在这里插入图片描述

一、绘制多个子图

1. 使用**plt.subplots**绘制均匀的子图

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

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

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

fig, axs = plt.subplots(2, 5, figsize=(10, 4), sharex=True, sharey=True)
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('横坐标')
        if j==0: axs[i][j].set_ylabel('纵坐标')
fig.tight_layout()
#fig.tight_layout(rect=[0, 0, 1, 0.95]) #用以解决figure标题重叠问题,前面四个参数可根据具体情况做适当修改
#plt.subplots_adjust(top=0.85) #对比就可以看出参数0.85的意义;
plt.subplots_adjust(top=0.8)

在这里插入图片描述

在调用subplot时一般需要传入三位数字,分别代表总行数,总列数,当前子图的index

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

N = 150
r = 2 * np.random.rand(N)
theta = 2 * np.pi * np.random.rand(N)
area = 200 * r**2
colors = theta

plt.subplot(projection='polar')
plt.scatter(theta, r, c=colors, s=area, cmap='hsv', alpha=0.75);

在这里插入图片描述

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])#
fig.suptitle('样例2', size=20)
for i in range(2):
    for j in range(5):
        ax = fig.add_subplot(spec[i, j])
        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()
plt.subplots_adjust(top=0.8)

在这里插入图片描述

通过切片可以实现子图的合并达到跨图的功能

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])
ax.scatter(np.random.randn(10), np.random.randn(10))
fig.tight_layout()
plt.subplots_adjust(top=0.8)

在这里插入图片描述

二、子图上的方法

直线

常用直线的画法为: axhline, axvline, axline (水平、垂直、任意方向)

fig, ax = plt.subplots(figsize=(4,3))
ax.axhline(0.5,0.2,0.8)
ax.axvline(0.5,0.2,0.8)

使用grid加灰色网格

ax.grid(True)

使用 set_xscale 可以设置坐标轴的规度(指对数坐标等)

fig, axs = plt.subplots(1, 2, figsize=(10, 4))
for j in range(2):
    axs[j].plot(list('abcd'), [10**i for i in range(4)])
    if j==0:
        axs[j].set_yscale('log')
    else:
        pass
fig.tight_layout()
plots(1, 2, figsize=(10, 4))
for j in range(2):
    axs[j].plot(list('abcd'), [10**i for i in range(4)])
    if j==0:
        axs[j].set_yscale('log')
    else:
        pass
fig.tight_layout()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值