19.函数subplots():创建一张画布带有多个子区的绘图模式

本文通过实例演示了如何使用Matplotlib库创建不同类型的图表。包括简单的折线图、散点图,以及更复杂的统计图形组合展示。介绍了如何调整子图布局,并展示了多种统计图形的组合方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


使用函数subplots(),只用一句matplotlib.pylot.subplots()调用命令就可以非常便捷的创建1行1列的网格布局的子区,同时创建一个画布对象。也就是说,函数subplots()返回值是一个(fig,ax)元组,其中fig是figure实例,ax可以是一个axis对象数组。因此,使用函数subplots()可以创建一张画布带有多个子区的绘图模式的网格布局。

import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np

mpl.rcParams["font.sans-serif"]=["FangSong"]
mpl.rcParams["axes.unicode_minus"]=False
font_style = dict(fontsize=18,weight="black")

#First create sample data:
x = np.linspace(0,2*np.pi,500)
y = np.sin(x)*np.cos(x)

# create just a figure and only onesubplot
fig,ax = plt.subplots(1,1,subplot_kw=dict(facecolor="cornflowerblue"))

ax.plot(x,y,"k--",lw=2)
ax.set_xlabel("时间(秒)",**font_style)
ax.set_ylabel("振幅",**font_style)
ax.set_title('简单折线图',**font_style)

ax.set_xlim(0,2*np.pi)
ax.set_ylim(-0.65,0.65)

ax.grid(ls=":",lw=1,color="gray",alpha=0.8)

#Show figure and subplot(s)
plt.show()


在这里插入图片描述

2.创建一张画布和两个子区的绘图模式

import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np

mpl.rcParams["font.sans-serif"]=["FangSong"]
mpl.rcParams["axes.unicode_minus"]=False
font_style = dict(fontsize=18,weight="black")

#First create sample data:
x = np.linspace(0,2*np.pi,500)
y = np.sin(x)*np.exp(-x)

# create just a figure and only onesubplot
fig,ax = plt.subplots(1,2,sharey=True)

# subplot(121)
ax1 = ax[0]
ax1.plot(x,y,"k--",lw=2)
ax1.set_title("折线图")
ax1.grid(ls=":",lw=1,color="gray",alpha=0.8)

# subplot(122)
ax2 = ax[1]
ax2.scatter(x,y,s=10,c="skyblue",marker="o")
ax2.set_title("散点图")

# create a figure title
plt.suptitle("创建一张画布和两个子区的绘图模式",**font_style)

# show figure and subplot(s)
plt.show()

在这里插入图片描述
如果想要改变子区边缘距离画布边缘的距离和子区边缘之间高度与宽度的距离,可以调用函数subplots_adjust(*arg,**kwargs)进行设置,其中关键字参数left,right,bottom,top,hspace和wspace都有默认值,而且是使用axes坐标轴系统度量的,即使用闭区间[0,1]的浮点数,前四个关键字可以调节子区距离画布的距离,关键字参数wspace控制子区间的宽度距离,关键参数hspace控制子区之间的高度距离。

3.多种统计图形组合展示

import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np

fig,ax = plt.subplots(2,3)

# subplot(231)
colors =["#8dd3c7","#ffffb3","pink"]
ax[0,0].bar([1,2,3],[0.6,0.2,0.8],color=colors,width=0.5,hatch="///",align="center")
ax[0,0].errorbar([1,2,3],[0.6,0.2,0.8],yerr=0.1,capsize=0,ecolor="#377eb8",fmt="o")
ax[0,0].set_ylim(0,1.0)

# subplot(232)
ax[0,1].errorbar([1,2,3],[20,30,36],xerr=2,ecolor="#4daf4a",elinewidth=2,fmt="s",label="ETN")
ax[0,1].legend(loc=3,fancybox=True,shadow=True,fontsize=10,borderaxespad=0.4)
ax[0,1].set_ylim(10,40)
ax[0,1].set_xlim(-2,6)
ax[0,1].grid(ls=":",lw=1,color="grey",alpha=0.5)

# subplot(233)
x3 = np.arange(1,10,0.5)
y3 = np.cos(x3)
ax[0,2].stem(x3,y3,basefmt="r-",linefmt="b-.",markerfmt="bo",label="life signal")
ax[0,2].legend(loc=2,fontsize=8,frameon=False,borderpad=0.0,borderaxespad=0.6)
ax[0,2].set_xlim(0,11)
ax[0,2].set_ylim(-1.1,1.1)

#subplot(2,3,4)
x4 = np.linspace(0,2*np.pi,500)
x4_1 = np.linspace(0,2*np.pi,1000)
y4 = np.cos(x4)*np.exp(-x4)
y4_1 = np.sin(2*x4_1)
line1,line2, = ax[1,0].plot(x4,y4,"k--",x4_1,y4_1,"r-",lw=2)
ax[1,0].legend((line1,line2),("energy","patience"),
               loc="upper center",
               fontsize=8,ncol=2,
               framealpha=0.3,
               mode="expand",
               columnspacing=2,
               borderpad=0.1)
ax[1,0].set_ylim(-2,2)
ax[1,0].set_xlim(0,2*np.pi)

# subplot(2,3,5)
x5 = np.random.rand(100)
ax[1,1].boxplot(x5,vert=False,showmeans=True,meanprops=dict(color="g"))
ax[1,1].set_yticks([])
ax[1,1].set_xlim(-1.1,1.1)
ax[1,1].set_ylabel("Micro SD Card")
ax[1,1].text(-1.0,1.2,"net weight",
             fontsize=20,
             style="italic",
             weight="black",
             family="monospace")

# subplot(2,3,6)
mu = 0.0
sigma = 1.0
x6 = np.random.randn(10000)
n,bins,patches = ax[1,2].hist(x6,bins=30,
                              histtype="stepfilled",
                              cumulative=True,
                              # normed=True,
                              color="cornflowerblue",
                              label="Test")
y = ((1/(np.sqrt(2*np.pi)*sigma))*np.exp(-0.5*(1/sigma*(bins-mu))**2))
y = y.cumsum()
y /= y[-1]
ax[1,2].plot(bins,y,"r--",linewidth=1.5,label="Theory")

ax[1,2].set_ylim(0.0,1.1)
ax[1,2].grid(ls=":",lw=1,color="grey",alpha=0.5)
ax[1,2].legend(loc="upper left",
               fontsize=8,
               shadow=True,
               fancybox=True,
               framealpha=0.8)
# adjust subplots() layout
plt.subplots_adjust()
plt.show()

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值