Matplotlib绘图-第三回:布局格式定方圆

  • 本文为DataWhale的Matplotlib训练营
  • 链接:https://datawhalechina.github.io/fantastic-matplotlib/index.html

文章目录

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

plt.subplots(nrows=1,ncols=1,,sharex=False,sharey=False,squeeze=True,subplot_kw=None,gridspec_kw=None,*fig_kw,)

  • nrows, ncols返回元素分别是画布和子图构成的列表,第一个数字为行,第二个为列,不传入时默认值都为1
  • 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()

plt.figure()

plt.subplot(2,2,1)
plt.plot([1,2], 'r')

plt.subplot(2,2,2)
plt.plot([1,2], 'b')

plt.subplot(224)
plt.plot([1,2], 'g');
  • 绘制极坐标系下
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);

非均匀子图: 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()
  • 图跨行或者跨列
    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)

ax = fig.add_subplot(spec[0, :3])
ax.scatter(np.random.randn(10), np.random.randn(10))

ax = fig.add_subplot(spec[0, 3:5])
ax.scatter(np.random.randn(10), np.random.randn(10))

ax = fig.add_subplot(spec[:, 5])
ax.scatter(np.random.randn(10), np.random.randn(10))

ax = fig.add_subplot(spec[1, 0])
ax.scatter(np.random.randn(10), np.random.randn(10))

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年的每月温度情况
import numpy as np
import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt

df = pd.read_csv("layout_ex1.csv")
df['year'] = df['Time'].apply(lambda x: x.split('-')[0])
df['month'] = df['Time'].apply(lambda x: x.split('-')[1])
df[['year','month']] = df[['year','month']].astype(int)

mpl.rc("font",family='MicroSoft YaHei',weight='bold')
fig, axs = plt.subplots(2, 5, figsize=(20, 4), sharex=True, sharey=True)
fig.suptitle('墨尔本1981年至1990年月温度曲线')
for i in range(2):
    for j in range(5):
        year = 1981+i*5+j
        axs[i][j].plot(range(1,13), df.loc[df['year']==year, 'Temperature'].values, marker = "*")
        axs[i][j].set_title('%d年'%(year))
        axs[i][j].set_xticks(range(1,13))
        if j==0: axs[i][j].set_ylabel('气温')
fig.tight_layout()
  • 画出数据的散点图和边际分布
fig = plt.figure(figsize=(8, 8))
spec = fig.add_gridspec(nrows=6, ncols=6)
ax1 = fig.add_subplot(spec[0:1,0:5])
ax1.hist(my_data_x,density = True,rwidth = 0.9)
ax1.axis("off")

ax2 = fig.add_subplot(spec[1:6,0:5])
ax2.scatter(my_data_x, my_data_y)
ax2.set_xlabel("my_data_x")
ax2.set_ylabel("my_data_y")
ax2.grid()

ax3 = fig.add_subplot(spec[1:6,5])
ax3.hist(my_data_y,orientation='horizontal',density = True,rwidth = 0.9)
ax3.axis("off")
fig.tight_layout()

Original: https://blog.csdn.net/weixin_41955255/article/details/122550674
Author: zhangkaihua88
Title: Matplotlib绘图-第三回:布局格式定方圆

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/769518/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球