第三回 布局格式定方圆
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
绘制均匀状态下的子图
返回元素分别是画布和子图构成的列表,第一个数字为行,第二个数字为列,不传入时默认值都为1
figsize
参数可以 指定整个画布的大小
sharex
和sharey
分别表示是否共享横轴和纵轴刻度
tight_layout
函数可以调整子图的相对大小使字符不会重叠
fig, axs = plt.subplots(2, 5, figsize=(10, 4), sharex=True, sharey=True)
fig.suptitle('example1', 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()
-
subplots
是基于OO模式的写法,可以显式创建一个或者多个axes对象,然后再对应子图对象上绘图 -
另外一种方法是使用
subplot
这样结余pyplot模式的写法,每次在指定位置新建一个子图,并且之后的
绘图操作都会指向当前子图,本质上subplot
也是Figure.add_subplot
的一种封装。在调用
subplot
时一般都需要传入三位数字,分别代表总行数,总列数,当前子图的index
plt.figure()
# 子图1
plt.subplot(2, 2, 1)
plt.plot([1, 2], 'r')
# 子图2
plt.subplot(3, 2, 2)
plt.plot([1, 2], 'b')
# 子图3
plt.subplot(224) #当三位数都小于10时,可以省略中间的逗号,这行命令等价于plt.subplot(2,2,4)
plt.plot([1, 2], 'g')
N = 1341
r = 2 * np.pi * 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)
如何用极坐标系画出类似的玫瑰图
import numpy as np
import math
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(10,6))#形成一个1000x600的一个白色窗口大小(玫瑰图的显示窗口)
ax = plt.subplot(111, polar=True)#順肘針 projection= 'polar'和polar=True等价
ax.set_theta_direction(-1)#极坐标正方向为顺时针
ax.set_theta_zero_location( 'N' )#极坐标0度的方向设置为正北方向
r = np.arange(100, 800, 20)#从100开始,步长20到800结束
theta = np.linspace(0, np.pi*2, len(r), endpoint=False)#会制柱状圏(从0开始到2Π,形成35个数字)
ax.bar(theta, r, #每个条的开始位置(度数),每个条对应的高度(因为r从100开始,所以圆心没有东西)
width=0.18, #每个条的宽度
color=np.random.random( (len(r),3)),#顔色 随机形成35行3列浮点数
align='edge', # 从指定角度的径向幵始(0度)如果是center,不能和0度对齐
bottom=100) #近高园心,没置偏高距高(从底部100开始)
#在圜心位置湿示文本
ax.text(np.pi*3/2-0.2, 90,'Origin',fontsize=14)#毎个柱的頂部星示文本表示大小
for angle, height in zip(theta, r):
if math.degrees(angle)>=180:
ax.text(angle+0.03, height+105, str(height),fontsize=height/80,rotation=-(math.degrees(angle)+90))#不星示坐 柝紬和网格銭
else:
ax.text(angle+0.03, height+105, str(height),fontsize=height/80,rotation=-(math.degrees(angle)+270))#旋转默认是逆时针
plt.axis('off')#緊湊布局,縮小外辺距(不显示极坐标的网格线)
plt.tight_layout()
plt.savefig( 'polarBar.png',dpi=480)
plt.show()
"""https://blog.csdn.net/qq_40660825/article/details/105045034"""
使用GridSpec
绘制非均匀子图
何为非均匀:
1.图的比例大小不同但没有跨行或跨列
2.图为跨列或跨行状态
利用 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('example2', size=20)
for i in range(2):
for j in range((4)):
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()
在上面的例子中出现了 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.5],
height_ratios=[1, 2])
fig.suptitle('Sample3', 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()
子图上的方法
补充,常用直线的画法: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)
ax.axline([0.3, 0.3],[0.7, 0.7])
"""使用grid可以加灰色网格"""
fig, ax = plt.subplots(figsize=(4, 3))
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()
思考题
- 墨尔本1981年至1990年的每月温度情况
ex1 = pd.read_csv('./layout_ex1.csv')
ex1.head()
- 请利用数据,画出如下图
import matplotlib.pyplot as plt
import numpy as np
data = np.random.randn(2, 150)
fig = plt.figure(figsize=(7,7))
spec = fig.add_gridspec(9,9,width_ratios=np.ones((9)),height_ratios=np.ones((9)))
ax1 = fig.add_subplot(spec[2:9,0:7])
ax2 = fig.add_subplot(spec[0:2,0:7],sharex=ax1) # 与子图1共享x坐标
ax3 = fig.add_subplot(spec[2:9,7:9],sharey=ax1) # 与子图1共享y坐标
#第一个子图
ax1.scatter(data[0],data[1])
ax1.set_ylabel('my_data_y',fontsize=10)
ax1.set_xlabel('my_data_y',fontsize=10)
ax1.grid(True)
#第二个子图
ax2.hist(data[0,:],rwidth=0.94)
# 隐藏x轴标度
ax2.get_xaxis().set_visible(False)
# 隐藏y轴标度
ax2.get_yaxis().set_visible(False)
# 关闭边框
for spine in ax2.spines.values():
spine.set_visible(False)
#第三个子图
ax3.hist(data[0,:],rwidth=0.94, orientation='horizontal')
# 隐藏x轴标度
ax3.get_xaxis().set_visible(False)
# 隐藏y轴标度
ax3.get_yaxis().set_visible(False)
# 关闭边框
for spine in ax3.spines.values():
spine.set_visible(False)
fig.tight_layout()