学习打卡3-布局格式定方圆

一、子图

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

import numpy as np
import pandas as pd
from matplotlib.font_manager import FontProperties
font = FontProperties(fname = "simsun.ttc",size=14)
import matplotlib.pyplot as plt
#np.random.randn()   正态分布
#np.random.rand()    均匀分布
fig, axs = plt.subplots(2, 5, figsize=(10, 4), sharex=True, sharey=True)
fig.suptitle('样例1', size=20,FontProperties = font)
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),FontProperties = font)
        axs[i][j].set_xlim(-5,5)
        axs[i][j].set_ylim(-5,5)
        if i==1: axs[i][j].set_xlabel('横坐标',FontProperties = font)
        if j==0: axs[i][j].set_ylabel('纵坐标',FontProperties = font)
fig.tight_layout()

在这里插入图片描述
补1:plt.subplot也可以绘制均匀状态下的子图。subplot时一般需要传入三位数字,分别代表总行数,总列数,当前子图的index

plt.figure()
# 子图1
plt.subplot(2,2,1) 
plt.plot([1,2], 'r')
# 子图2
plt.subplot(2,2,2)
plt.plot([1,2], 'b')
# 子图3
plt.subplot(2,2,3)
plt.plot([1,2], 'y')
#子图4
plt.subplot(224)  # 当三位数都小于10时,可以省略中间的逗号,这行命令等价于plt.subplot(2,2,4) 
plt.plot([1,2], 'g');

在这里插入图片描述

补2:除了常规的直角坐标系,也可以通过projection方法创建极坐标系下的图表

N = 150
r = 2 * np.random.rand(N)#服从“0-1”均匀分布的随机样本值,取值范围[0-1)
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);

在这里插入图片描述
练一练:请思考如何用极坐标系画出玫瑰图

import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure(figsize=(10,6))
ax = plt.subplot(111,projection = 'polar')
ax.set_theta_direction(-1)
ax.set_theta_zero_location('N')
r = np.arange(100,800,20)
theta = np.linspace(0,np.pi*2,len(r),endpoint=False)
ax.bar(theta,r,width=0.18,color=np.random.random((len(r),3)),align='edge',bottom=100)
ax.text(np.pi*3/2-0.2,90,'Origin',fontsize=14)
for angle,height in zip(theta,r):
    ax.text(angle+0.03,height+120,str(height),fontsize=height/80)
plt.axis('off')
plt.tight_layout()
plt.show()

在这里插入图片描述
2.使用 GridSpec 绘制非均匀子图

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,FontProperties = font)
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),FontProperties = font)
        if i==1: ax.set_xlabel('横坐标',FontProperties = font)
        if j==0: ax.set_ylabel('纵坐标',FontProperties = font)
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,FontProperties = font)
# 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()

在这里插入图片描述

二、子图上的方法

常用直线的画法为: 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 可以加灰色网格
在这里插入图片描述
使用 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()

在这里插入图片描述

三、思考题

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

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
font = FontProperties(fname = "simsun.ttc",size=14)
data = pd.read_csv('layout_ex1.csv')
data.head(13)

在这里插入图片描述

time = pd.to_datetime(data['Time'])
data['Month'] = time.dt.month
data['Year'] = time.dt.year
fig, axs = plt.subplots(2, 5, figsize=(20, 4), sharex=True, sharey=True)
fig.suptitle('墨尔本1981年至1990年月温度曲线', size=20,FontProperties = font)
K=0
for i in range(2):
    for j in range(5):
        axs[i][j].plot(data['Month'][K*12:(K+1)*12],data['Temperature'][K*12:(K+1)*12])
        axs[i][j].scatter(data['Month'][K*12:(K+1)*12],data['Temperature'][K*12:(K+1)*12],marker='*')
        axs[i][j].set_xlim(1,12)
        axs[i][j].set_ylim(3,18)
        axs[i][j].set_title('%d年'%(1880+K+1),FontProperties = font)
        k = K+1
        if j==0: axs[i][j].set_ylabel('气温',FontProperties = font)
fig.tight_layout()

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

data = np.random.randn(2, 150) 
x = data[0]
y = data[1]
fig = plt.figure(figsize=(5, 5))
spec = fig.add_gridspec(nrows=2, ncols=2, width_ratios=[4,1], height_ratios=[1,4])
#sub1
ax1 = fig.add_subplot(spec[1,0])
ax1.scatter(x,y)
ax1.grid(True)
ax1.set_xlabel('my_data_x') 
ax1.set_ylabel('my_data_y') 
 
#sub2
ax2 = fig.add_subplot(spec[0,0],sharex=ax1)
ax2.hist(x,rwidth=5)
ax2.axis('off')
ax2.spines['top'].set_visible(False)
ax2.spines['right'].set_visible(False)
ax2.spines['bottom'].set_visible(False)
ax2.spines['left'].set_visible(False)
 
#sub3
ax3 = fig.add_subplot(spec[1,1],sharey=ax1)
ax3.hist(y,rwidth=5,orientation='horizontal')
ax3.axis('off')
ax3.spines['top'].set_visible(False)
ax3.spines['right'].set_visible(False)
ax3.spines['bottom'].set_visible(False)
ax3.spines['left'].set_visible(False)
fig.tight_layout()
plt.show( )

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值