Datawhale学习打卡-04(Matplotlib)

Datawhale学习打卡-04(Matplotlib)

第三回:布局格式定方圆

参考资料:第三回:布局格式定方圆

常用基础设置抬头

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   #用来正常显示负号

一、子图

直角坐标系

fig, axs = plt.subplots(2, 5, figsize=(10, 4), sharex=True, sharey=True)
"""
返回元素分别是画布和子图构成的列表,
subplots第一个数字为行数第二个为列数,
figsize 参数可以指定整个画布的大小,
sharex 和 sharey 分别表示是否共享横轴和纵轴刻度,
"""
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()#tight_layout 函数可以调整子图的相对大小使字符不会重叠

极坐标系

N = 150
r = 2 * np.random.rand(N)
theta = 200* 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);

非均匀子图

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])
#利用 add_gridspec 可以指定相对宽度比例 width_ratios 和相对高度比例参数 height_ratios
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()

在这里插入图片描述

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])#此处必须指定nrows和ncols应该是实参用法
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()

在这里插入图片描述

二、子图上的方法

在 ax 对象上定义了和 plt 类似的图形绘制函数,常用的有: plot, hist, scatter, bar, barh, pie

fig, ax = plt.subplots(figsize=(4,3))
ax.plot([1,2],[2,1]);
#绘制折线

在这里插入图片描述

fig, ax = plt.subplots(figsize=(4,3))
ax.hist(np.random.randn(1000));
#绘制直方图

在这里插入图片描述

常用直线的画法为: axhline, axvline, axline (水平、垂直、任意方向)

fig, ax = plt.subplots(figsize=(4,3))
ax.axhline(0.5,0.2,0.8) # 三个参数分别是 (y值,x最小值、x最大值) [后两个要取0-1之间的值,代表线占图的比例]
ax.axvline(0.5,0.2,0.8)# 三个参数分别是 (x值,y最小值、y最大值)
ax.axline([0.3,0.3],[0.7,0.7]); # 直线中两个点的横纵坐标

在这里插入图片描述

使用 grid 加灰色网格

fig, ax = plt.subplots(figsize=(4,3))
ax.grid(True)

在这里插入图片描述

使用 set_xscale, set_title, set_xlabel 分别可以设置坐标轴的规度(指对数坐标等)、标题、轴名

fig, axs = plt.subplots(1, 2, figsize=(10, 4))
fig.suptitle('大标题', size=20)
for j in range(2):
    axs[j].plot(list('abcd'), [10**i for i in range(4)]) # 用一个list设置横坐标的的值
    if j==0:
        axs[j].set_yscale('log') # 对数
        axs[j].set_title('子标题1')
        axs[j].set_ylabel('对数坐标')
    else:
        axs[j].set_title('子标题1')
        axs[j].set_ylabel('普通坐标')
fig.tight_layout()

在这里插入图片描述

与一般的 plt 方法类似, legend, annotate, arrow, text 对象也可以进行相应的绘制

fig, ax = plt.subplots()
ax.arrow(0, 0, 1, 1, head_width=0.03, head_length=0.05, facecolor='red', edgecolor='blue')
# 前四个参数(x,y,dx,dy)可以不用括号分开 所以画的arrow的起始点为(x,y)终止点为(x+dy,x+dy) 
ax.text(x=0, y=0,s='这是一段文字', fontsize=16, rotation=70, rotation_mode='anchor', color='green')
# ax.text(x,y,s) 分别是放text的位置的横纵坐标以及要放的字符串  rotation_mode=‘anchor’是先对齐再旋转,与“default”结果有一点区别
ax.annotate('这是中点', xy=(0.5, 0.5), xytext=(0.8, 0.2), arrowprops=dict(facecolor='yellow', edgecolor='black'), fontsize=16);

在这里插入图片描述

设置图例的位置

fig, ax = plt.subplots()
ax.plot([1,2],[2,1],label="line1") # 图例
ax.plot([1,1],[1,2],label="line1")
ax.legend(loc=1);  
# 0->best,1--->upper right,2---->upper left,3--->lower left
# 4--->lower right,5-->right,6--->center left,7--->center right
#8--->lower center # 9--->upper center # 10-->center

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值