matplotlib、seaborn画图常用功能速查表

图形

bar

横向:barh

boxplot

https://www.freesion.com/article/65641222337/

子图(ax)

  • 设置子图间距

    fig, axes = plt.subplots(n_row, n_col, figsize=(7, 3), dpi=100)
    fig.subplots_adjust(hspace=0.1, wspace=0.3)  # hspace是上下间距,wspace是左右间距
    
  • 设置子图坐标轴间距相等

    ax.axis('equal')  # 如果使用plt,则为plt.axis(equal)
    
  • 子图排版:fig.add_gridspec、ax.inset_axes

    # 参考:https://matplotlib.org/stable/gallery/lines_bars_and_markers/scatter_hist.html
    import matplotlib.gridspec as gridspec
    
    fig = plt.figure(figsize=(4, 4))
    
    # 创建主图,上、右各留出25%的空间给侧边图
    ax = fig.add_gridspec(top=0.75, right=0.75).subplots()
    
    # 创建侧边图。ax.inset_axes的值>1时将侧边图放置在主图的右侧、上侧,<0时放置在左侧、下侧。
    ax_histx = ax.inset_axes([0, 1.05, 1, 0.25], sharex=ax)
    ax_histy = ax.inset_axes([1.05, 0, 0.25, 1], sharey=ax)
    
    # 数据可视化
    x = np.random.randn(1000)
    y = np.random.randn(1000)
    ax.scatter(x, y)
    ax_histx.hist(x)
    ax_histy.hist(y, orientation='horizontal')
    
    # 隐藏侧边图的tick label
    ax_histx.tick_params(axis="x", labelbottom=False)
    ax_histy.tick_params(axis="y", labelleft=False)
    

    子图排版

  • 设置子图标题,并放在图像下方

    ax = plt.gca()
    ax.set_title("(a)", y=-0.1)
    
  • 获取图像大小

    fig = plt.gcf()
    print(fig.get_size_inches())
    

图例、标签、注释

  • 中文、负号
    from matplotlib import rcParams
    rcParams['font.family'] = 'SimHei'
    rcParams['axes.unicode_minus'] = False
    
  • 各种添加图例的方法:matplotlib6 – 添加 图例 legend
  • 多子图共用colorbar:Matplotlib 系列:colorbar 的设置
  • 图例放在外侧
    ax.legend(loc="upper left", bbox_to_anchor=(1, 1))  # loc:图例定位点。bbox_to_anchor:定位点相对于图的位置
    
  • 设置label
    ax = plt.gca()
    ax.set_ylabel('Y', rotation=0, color='r',
    	labelpad=10  # label到轴的距离,可以是负数
    	)
    
  • 添加注释
    ax.text(1, 1, "在图中坐标(1,1)处添加文字")
    ax.text(0.9, 0.8, "在ax的(90%, 80%)处添加文字", fontsize=12, transform=ax.transAxes)
    
  • 设置坐标轴
    ax = plt.gca()
    # tick位置
    ax.set_xticks([1,2,3,4])
    # tick标签
    ax.set_xticklabels(['a', 'b', 'c', 'd'],
    	rotation=40, 
    	ha='right', rotation_mode='anchor'  # 旋转+使标签的右上角对齐刻度
    )
    # tick字体大小,颜色
    ax.tick_params(axis='y', labelsize=12, 
    	colors='k'  # 此处控制的是tick的label颜色,不是xlabel。
    	)
    # 科学计数法
    ax.ticklabel_format(axis="x", style="sci", scilimits=(0,0))
    

在这里插入图片描述

颜色

获取颜色

  • matplotlib
    matplotlib颜色文档
    在这里插入图片描述

    # 获取颜色
    plt.cm.Pastel1(0)
    	# out: (0.984313725490196, 0.7058823529411765, 0.6823529411764706, 1.0)
    
  • seaborn
    seaborn颜色文档
    在这里插入图片描述

    # 获取颜色
    sns.color_palette()[0]
    # out: (0.2980392156862745, 0.4470588235294118, 0.6901960784313725)
    

保存

fig.tight_layout(pad=0.2)  # 调整子图之间、子图周围的填充大小
plt.savefig("filename", bbox_inches='tight')  # 去除四周的白边

fig, axes = plt.subplots(1,1)
fig.savefig(**kwargs)

综合示例

子图+boxplot

import matplotlib.patches as mpatches
import matplotlib.pyplot as plt
import numpy as np

# 生成18条数据,3个一组画到6个子图里
data = [np.random.random(5)*np.random.randint(1,5) for i in range(18)]
title_list = [f"Subplot{i}" for i in range(1,7)]

# 定义颜色,用Pastel1色卡
colors=[plt.cm.Pastel1(i) for i in range(3)]

# 定义图例
labels = ['Series A', 'Series B', 'Series C']

# 设置子图数量、分辨率、大小、坐标轴
fig, axes = plt.subplots(2, 3, sharex=True, sharey=True, figsize=(6,4), dpi=100)
fig.subplots_adjust(hspace=0.3, wspace=0.3)
axes = axes.flatten()  # axes是[n_row, n_col]形状的array,为了访问方便将其变为一维
for i in range(6):
    p1 = axes[i].boxplot(data[i*3:(i+1)*3], labels=labels, patch_artist=True)
    axes[i].set_title(title_list[i])
    axes[i].get_xaxis().set_visible(False)
    for box, c in zip(p1['boxes'], colors):
        # 箱体边框颜色
        # box.set(color=c, linewidth=1.5)
        # 箱体内部填充颜色
        box.set(facecolor=c)

# 图例
patches = []
for c, label in zip(colors, labels):
    patch = mpatches.Patch(color=c, label=label)
    patches.append(patch)
plt.legend(handles=patches, loc='upper left', bbox_to_anchor=(1, 1))  # 将图例画在右侧。bbox_to_anchor(x, y):将图例的loc位置放在整张图的(x,y)比例处

在这里插入图片描述

logscale+花式tick

import matplotlib.pyplot as plt

# 读取数据的过程略,将数据读入df(pd.DataFrame)

fig, axes = plt.subplots(1, 2, dpi=300, figsize=(10,3))
fig.subplots_adjust(wspace=0.2) 

axes[0].plot(df["time"], df["lat0"], label="Latitude 0°", color="black")
axes[0].plot(df["time"], df["lat30"], label="Latitude 30°", color="blue")
axes[0].plot(df["time"], df["lat60"], label="Latitude 60°", color="red")
axes[0].legend(loc='lower center', fontsize=8, edgecolor="black")
axes[0].set_ylabel("Surface temperature (K)", fontsize=10)
axes[0].set_xlabel("Local time", fontsize=10)
axes[0].xaxis.set_major_locator(plt.MultipleLocator(6))
axes[0].xaxis.set_minor_locator(plt.MultipleLocator(1))
axes[0].yaxis.set_minor_locator(plt.MultipleLocator(10))
axes[0].tick_params(which="minor", top=True, right=True, length=1.5, width=0.5)
axes[0].tick_params(which="major", labelsize=8, top=True, right=True, length=3, width=0.8)
axes[0].text(1, 370, "(a)", fontsize=10)
axes[0].set_xlim([0, 24])
axes[0].set_ylim([50, 400])

axes[1].plot(df2["6 AM"], df2["depth"], color="blue", linewidth=0.8)
axes[1].text(60, 0.009, "6 AM", color="blue", fontsize=8)
axes[1].plot(df2["8 AM"], df2["depth"], color="gold", linewidth=0.8)
axes[1].text(290, 0.009, "8 AM", color="gold", fontsize=8)
axes[1].plot(df2["10 AM"], df2["depth"], color="orange", linewidth=0.8)
axes[1].text(340, 0.009, "10 AM", color="orange", fontsize=8)
axes[1].plot(df2["12 AM"], df2["depth"], color="cyan", linewidth=0.8)
axes[1].text(90, 0.009, "12 AM", color="cyan", fontsize=8)
axes[1].plot(df2["6 PM"], df2["depth"], color="lime", linewidth=0.8)
axes[1].text(130, 0.009, "6 PM", color="lime", fontsize=8)
axes[1].plot(df2["12 PM"], df2["depth"], color="red", linewidth=0.8)
axes[1].text(380, 0.009, "12 PM", color="red", fontsize=8)

# 坐标轴通用
axes[1].tick_params(which="minor", top=True, right=True, length=1.5, width=0.5)
axes[1].tick_params(which="major", labelsize=8, top=True, right=True, length=3, width=0.8)
# 谢谢大神 https://stackoverflow.com/questions/6998697/in-matplotlib-how-do-you-display-an-axis-on-both-sides-of-the-figure
# x轴
axes[1].set_xlim([50, 400])
axes[1].xaxis.set_major_locator(plt.MultipleLocator(50))
axes[1].xaxis.set_minor_locator(plt.MultipleLocator(10))
axes[1].set_xlabel("Temperature (K)", fontsize=10)
# y轴
axes[1].set_ylim([0.01, 1])
axes[1].set_yscale("log")
axes[1].yaxis.set_major_formatter(ticker.FuncFormatter(lambda y, _: '{:g}'.format(y)))  # log显示格式
# 谢谢大神 https://stackoverflow.com/questions/21920233/matplotlib-log-scale-tick-label-number-formatting/21920673#21920673
axes[1].invert_yaxis()  # y轴翻转
axes[1].set_ylabel("Depth (m)", fontsize=10)

axes[1].text(60, 0.015, "(b)", fontsize=10)

请添加图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值