文章目录

  • 前言
  • 1 子图
    • 1.1 使用 plt.subplots 绘制均匀状态下的子图
    • 1.2 使用 GridSpec 绘制非均匀子图
  • 2 子图上的方法
    • 2.1 plot-线的绘制
    • 2.2 hist-直方图的绘制
    • 2.3 对图像的特殊设置
  • 作业

前言

《第三回:布局格式定方圆》笔记。


1 子图

1.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()

使用plt.subplot()prejection船舰极坐标系下的图表:

N = 150
r = 2 * np.random.rand(N)
theta = 2 * np.pi * np.random.rand(N)
area = 200 * r**2
colors = thetaplt.subplot(projection='polar')
plt.scatter(theta, r, c=colors, s=area, cmap='hsv', alpha=0.75)

1.2 使用 GridSpec 绘制非均匀子图

非均匀包含两层含义:

  1. 图的比例大小不同但没有跨行或跨列
  2. 图为跨列或跨行状态

第一种含义:


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]) # gridspec子图。可以通过切片获取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()

第二种:
可以这样理解,我们设置拥有2行3列子图的figure,然后把其中几个子图合并,就得到了大小不同的子图。加入我们合并其中2个子图,那么本来2行3列一共6个子图就会变成5个,不信我们试试看:

fig = plt.figure(figsize=(10, 4))
spec = fig.add_gridspec(nrows=2, ncols=6, width_ratios=[1,1,1,1,1,1], height_ratios=[1,1])
fig.suptitle('样例3', size=20)
#sub1
ax = fig.add_subplot(spec[0,0])
ax.scatter(np.random.randn(10), np.random.randn(10))
#sub2
ax = fig.add_subplot(spec[0,1])
ax.scatter(np.random.randn(10), np.random.randn(10))
#sub3
ax = fig.add_subplot(spec[:,2])
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])
ax.scatter(np.random.randn(10), np.random.randn(10))fig.tight_layout()

fig = plt.figure(figsize=(10, 4))
spec = fig.add_gridspec(nrows=2, ncols=6, width_ratios=[1,1,1,1,1,1], height_ratios=[1,1])
fig.suptitle('样例3', size=20)
# sub1
ax = fig.add_subplot(spec[0,0:2])
ax.scatter(np.random.randn(10), np.random.randn(10))
# sub2
ax = fig.add_subplot(spec[0,2])
ax.scatter(np.random.randn(10), np.random.randn(10))
# sub3
ax = fig.add_subplot(spec[1:,0])
ax.scatter(np.random.randn(10), np.random.randn(10))
# sub4
ax = fig.add_subplot(spec[1,1])
ax.scatter(np.random.randn(10), np.random.randn(10))
# sub5
ax = fig.add_subplot(spec[1, 2])
ax.scatter(np.random.randn(10), np.random.randn(10))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])
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()

2 子图上的方法

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

plot, hist, scatter, bar, barh, pie

2.1 plot-线的绘制

  • 绘制任意直线
fig, ax = plt.subplots(figsize=(4,3))
ax.plot([1,2],[2,1])

fig, ax = plt.subplots(figsize=(4,3))
ax.plot(np.random.rand(10),np.random.rand(10))

fig, ax = plt.subplots(figsize=(4,3))
ax.axhline(0.5,0,0.8) # 0.5是y的取值;后两个参数的意思是从左到右,占整个图的0%的位置和百分之80%的位置
ax.axvline(0.5,0.2,0.8) # 0.5是y的取值;后两个参数的意思是从左到右,占整个图的20%的位置和80%的位置
ax.axline([0.3,0.3],[0.7,0.7]) # 经过这两个坐标[0.3,0.3],[0.7.0.7

2.2 hist-直方图的绘制

fig, ax = plt.subplots(figsize=(4,3))
ax.hist(np.random.randn(1000))


使矩形之间产生间隔:

fig, ax = plt.subplots(figsize=(4,3))
ax.hist(np.random.randn(1000),rwidth=0.9)

2.3 对图像的特殊设置

  • 使用 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)])if j==0:axs[j].set_yscale('log')axs[j].set_title('子标题1')axs[j].set_ylabel('对数坐标')axs[j].set_xlabel('hello 是我 你们的好朋友 xlabel')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')
ax.text(x=0, y=0,s='这是一段文字', fontsize=16, rotation=70, rotation_mode='anchor', color='green')
ax.annotate('这是中点', xy=(0.5, 0.5), xytext=(0.7, 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)

其中,图例的 loc 参数如下:

string code
best 0
upper right 1
upper left 2
lower left 3
lower right 4
right 5
center left 6
center right 7
lower center 8
upper center 9
center 10

大部分操作都是通过axex来实现的,所以说axex是画图时最核心的部分。

作业

1. 墨尔本1981年至1990年的每月温度情况

import matplotlib.pyplot as plt
from matplotlib.pyplot import MultipleLocator
import pandas as pd
import numpy as np
plt.rcParams['font.sans-serif'] = ['SimHei'] #设置字体为SimHei显示中文
plt.rcParams['axes.unicode_minus'] = False #设置正常显示字符data = pd.read_csv('./layout_ex1.csv')fig, axs = plt.subplots(2,5,figsize=(20,5),sharex=True,sharey=True)
fig.suptitle('墨尔本1981年至1990年月温度曲线',size=20)index = 0
for i in range(2):for j in range(5):axs[i][j].plot(np.arange(1,13),data['Temperature'].values[index*12:(index*12+12)],'o-')axs[i][j].set_title('%s年'%data['Time'].values[index][:4])axs[i][j].xaxis.set_major_locator(MultipleLocator(1)) #把横坐标设置为1的倍数axs[i][j].yaxis.set_major_locator(MultipleLocator(5)) #把纵坐标设置为5的倍数if(j==0):axs[i][j].set_ylabel('气温')index += 1fig.tight_layout()

2. 画出数据的散点图和边际分布

import matplotlib.pyplot as plt
import numpy as npdata = 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()

数据可视化组队学习:《Task03 - 布局格式定方圆》笔记相关推荐

  1. 数据可视化组队学习:《Task02 - 艺术画笔见乾坤》笔记

    文章目录 前言 1 概述 1.1 matplotlib的使用逻辑 1.2 matplotlib的三层api 1.3 Artist类的结构 1.4 matplotlib标准用法 2 自定义你的Artis ...

  2. 数据可视化组队学习:《Task01 - Matplotlib初相识》笔记

    第一回:Matplotlib初相识 本文为组队学习任务01学习笔记. Matplotlib简要总结 Matplotlib的结构 一个完整的Matplotlib图像包括四个层级: Figure:容纳所有 ...

  3. 数据可视化组队学习:《Task04 - 文字图例尽眉目》笔记

    文章目录 前言 1 Figure和Axes的文本 1.1 text 1.2 title和set_title 1.3 figtext和text 1.4 suptitle 1.5 xlabel和ylabe ...

  4. 数据可视化组队学习:《Task06 - 场景案例显神通》笔记

    文章目录 前言 1 展示趋势变化(Evolution) 1.1 折线图 1.1.1 简单线图 1.1.2 突出某一重点的多线图 1.2 面积图 1.3 堆积面积图 2 展示分布关系 2.1 小提琴图 ...

  5. 数据可视化组队学习:《Task05 - 样式色彩秀芳华》笔记

    文章目录 前言 1 matplotlib全局样式设定 1.1 matplotlib自带的样式 1.2 打造属于自己的全局绘图样式 1.2.1 使用.mplstyle文件来设置 1.2.2 设置rcpa ...

  6. 数据可视化系列(一):Matplotlib初相识

    前言 期待了好久的datawhale可视化教程终于出来了,这次标题狠有文艺范儿,哈哈哈 这次我主要目的是最近要写篇论文,也正好为以后建模画图打捞基础~ 大家可以多看看官方教程: 中文官方网站:http ...

  7. datawhale6月组队学习-task01

    datawhale6月组队学习-task01 1.数据加载 利用kaggle网站的泰坦尼克号数据集进行学习分析 下载网址: https://www.kaggle.com/c/titanic/overv ...

  8. datawhale9月组队学习task01环境搭建,初始数据库

    Datawhale9月组队学习 task01环境搭建,初始数据库 文章目录 Datawhale9月组队学习 task01环境搭建,初始数据库 一.环境搭建 1.MySQL 8.0的安装 2. 连接 M ...

  9. 斯坦福大学数据可视化课程学习笔记:第一节 可视化的发展与目标

    <斯坦福大学数据可视化课程学习笔记>课程资源来自于斯坦福大学数据可视化课程,是我所在团队实习生提升计划的一部分.本系列是 "秉姝" 同学在学习过程中记录和整理的学习笔记 ...

最新文章

  1. html 商品展示框
  2. iOS app性能优化的那些事
  3. 米的换算单位和公式_求小学数学的公式、换算和单位转英文字母(米cm)
  4. 带你了解2020年全新【思科专家级认证CCIE】
  5. CSDN专家分和博客系统积分获得规则!
  6. Python爬取js动态添加的内容
  7. arcgis加载天地图_ArcGIS Runtime SDK for Android100.5.0端加载天地图服务
  8. centos linux 禁止ping
  9. mysql延时优化教程_Mysql优化之延迟索引和分页优化_MySQL
  10. 限免!百名 AI 大咖,20 大技术和行业论坛,邀你加入群聊
  11. rhel6.4部署tomcat
  12. (libgdx学习)Net的使用
  13. 图片预加载插件 preLoad.js
  14. 斐波那契查找算法中为什么需要把数组长度扩充到f[k]-1而不是f[k]或者f[k+1]
  15. 装饰者模式的应用:react高阶组件和ES6 装饰器
  16. destoon php文件,destoon代码从头到尾捋一遍
  17. 汽车研发企业试验数据管理系统建设研究
  18. Pandas_规整数据_转换数据_melt()
  19. 【面试技巧】十大面试必胜绝招
  20. android 常用的代码

热门文章

  1. 最长上升子序列问题 (LIS)
  2. poj 1948(搜索+剪枝)
  3. Python把数据存储到CSV
  4. Golang之var、new与make、简短声明
  5. Serverless的理解
  6. csv文件导入sqlite
  7. ASP.NET页面刷新的几种实现方法
  8. springnbsp;security总结nbsp;太有用了!!
  9. combobox DataGridView
  10. STM32学习笔记——DMA控制器(向原子哥学习)