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
参数可以指定整个画布的大小
sharex
和 sharey
分别表示是否共享横轴和纵轴刻度
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()