datawhale学习-数据可视化(3)

一、子图

1. 使用 plt.subplots 绘制均匀状态下的子图

返回元素分别是画布和子图构成的列表,第一个数字为行,第二个为列

figsize 参数可以指定整个画布的大小

sharex 和 sharey 分别表示是否共享横轴和纵轴刻度

tight_layout 函数可以调整子图的相对大小使字符不会重叠

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

的的的

2. 使用 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)
# 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()

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-UwKcZPMY-1608468707955)(output_4_0.png)]

在这里插入图片描述

二、子图上的方法

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

fig, ax = plt.subplots(figsize=(4,3))
ax.plot(np.linspace(0,1,1000),np.random.randn(1000))
[<matplotlib.lines.Line2D at 0x7fccc753a410>]

在这里插入图片描述

fig, ax = plt.subplots(figsize=(4,3))
ax.hist(np.random.randn(300))
(array([ 3.,  6.,  8., 28., 61., 75., 55., 38., 21.,  5.]),
 array([-3.6036411 , -2.97937539, -2.35510968, -1.73084398, -1.10657827,
        -0.48231256,  0.14195315,  0.76621886,  1.39048457,  2.01475028,
         2.63901598]),
 <BarContainer object of 10 artists>)

在这里插入图片描述

Axes.axhline(self, y=0, xmin=0, xmax=1) #0-1之间,默认0,0,1

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

fig, ax = plt.subplots(figsize=(4,3))
ax.axhline(0.5,0.8)
ax.axvline(0.5,0.2,0.8)
ax.axline([0.3,0.3],[0.7,0.7])
ax.grid(True)

在这里插入图片描述

#使用 set_xscale, set_title, set_xlabel 分别可以设置坐标轴的规度(指对数坐标等)、标题、轴名
#"linear", "log", "symlog", "logit", ...}
fig,axs = plt.subplots(1,2,figsize=(10, 4))
fig.suptitle("big title",size=10)
for i in range(len(axs)):
    axs[i].plot(list('abcd'), [10**i for i in range(4)]) #可以不断的添加
    axs[i].plot(np.linspace(0,1,500),np.random.randn(500))
    axs[i].set_title("title"+str(i))
    axs[i].set_ylabel('log coordinate '+str(i))
    axs[i].set_yscale('log')

fig.tight_layout()
'''
for j in range(2):
    
    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, 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.8, 0.2), arrowprops=dict(facecolor='yellow', edgecolor='black'), fontsize=16)
Text(0.8, 0.2, '这是中点')

在这里插入图片描述

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
'''

在这里插入图片描述

作业

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

ex1 = pd.read_csv('data/layout_ex1.csv')
ex1.head()
TimeTemperature
01981-0117.712903
11981-0217.678571
21981-0313.500000
31981-0412.356667
41981-059.490323
np.linspace(1,12,12)
array([ 1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,  9., 10., 11., 12.])
fig = plt.figure(figsize=(10, 4))
#spec = fig.add_gridspec(nrows=2, ncols=5, width_ratios=[1,1,1,1,1], height_ratios=[1,1])
fig.suptitle('墨尔本1981至1990年月温度变化', size=20)
for i in range(2):
    for j in range(5):
        ax = fig.add_subplot(spec[i, j])
        ax.plot(np.linspace(0,12,12), ex1['Temperature'][(12*(i*5+j)):(12*(i*5+j)+12)],'o','red')
        ax.plot(np.linspace(0,12,12), ex1['Temperature'][(12*(i*5+j)):(12*(i*5+j)+12)])
        ax.set_title('%d年'%(i*5+j+1981))
        if i==1: ax.set_xlim(1,12)
        if j==0: ax.set_ylabel('纵坐标')
fig.tight_layout()

在这里插入图片描述

作业2:画出数据的散点图和边际分布

参考链接

用 np.random.randn(2, 150) 生成一组二维数据,使用两种非均匀子图的分割方法,做出该数据对应的散点图和边际分布图

import seaborn as sns
data=np.random.randn(2, 150)
data=pd.DataFrame(data.T)
data
#fig,axs = plt.subplots()
#p = sns.jointplot(data=data)
p2 = sns.jointplot(x=data[0],y=data[1],data=data,kind="scatter")  #终于成功啦啦啦!!!
#x和y的值要取对,如果data里面有确定的str类型的索引的话,可以直接用索引

在这里插入图片描述

#一开始有问题,变成了下面这样子,这是因为没有设置x索引 和y索引,默认是用0-150的这个索引作为横坐标,绘制出的是x-y1 和 x-y2的scatter图,所以分布才会是这种趋势
p = sns.jointplot(data=data,kind="scatter")

在这里插入图片描述

#祭出一个网上的参考教程,比较典型,应该用哪个索引体现的很明显
tips = sns.load_dataset("tips")
tips
g = sns.jointplot(x="total_bill", y="tip", data=tips)
g2 = sns.jointplot(x="total_bill", y="tip", data=tips, kind="scatter")
total_billtipsexsmokerdaytimesize
016.991.01FemaleNoSunDinner2
110.341.66MaleNoSunDinner3
221.013.50MaleNoSunDinner3
323.683.31MaleNoSunDinner2
424.593.61FemaleNoSunDinner4
........................
23929.035.92MaleNoSatDinner3
24027.182.00FemaleYesSatDinner2
24122.672.00MaleYesSatDinner2
24217.821.75MaleNoSatDinner2
24318.783.00FemaleNoThurDinner2

244 rows × 7 columns

g = sns.jointplot(x="total_bill", y="tip", data=tips)
#g2 = sns.jointplot(x="total_bill", y="tip", data=tips, kind="scatter")

在这里插入图片描述

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值