教程与目录

一、子图
1.使用 plt.subplots 绘制均匀状态下的子图
2.使用 GridSpec 绘制非均匀子图
二、子图上的方法
思考题

收获

  1. 系统了解了子图的绘制方法
  2. 了解了子图也能化成下面样例3的形式,感觉很有趣
  3. 让我感觉有意思的是,方法”set_xscale”可以直接把坐标替换为指数或者对数;之前的话我可能就得生成对应表变量再画图了

image.png

思考题

  1. 墨尔本1981年至1990年的每月温度情况,要求图片:

第三讲 子图相关 - 图2

  1. import numpy as np
  2. import pandas as pd
  3. import matplotlib as mpl
  4. import matplotlib.pyplot as plt
  5. df = pd.read_csv(".\data\layout_ex1.csv")
  6. df['year'] = df['Time'].apply(lambda x: x.split('-')[0])
  7. df['month'] = df['Time'].apply(lambda x: x.split('-')[1])
  8. df[['year','month']] = df[['year','month']].astype(int)
  9. mpl.rc("font",family='MicroSoft YaHei',weight='bold')
  10. fig, axs = plt.subplots(2, 5, figsize=(20, 4), sharex=True, sharey=True)
  11. fig.suptitle(u'墨尔本1981年至1990年月温度曲线', size=20)
  12. for i in range(2):
  13. for j in range(5):
  14. year = 1981+i*5+j
  15. axs[i][j].plot(range(1,13), df.loc[df['year']==year, 'Temperature'].values, marker = "*")
  16. axs[i][j].set_title('%d年'%(year))
  17. axs[i][j].set_xticks(range(1,13))
  18. if j==0: axs[i][j].set_ylabel('气温')
  19. fig.tight_layout()

image.png

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

第三讲 子图相关 - 图4

  1. import numpy as np
  2. import pandas as pd
  3. import matplotlib as mpl
  4. import matplotlib.pyplot as plt
  5. data = np.random.randn(2, 150)
  6. fig = plt.figure(figsize=(8,8))
  7. spec = fig.add_gridspec(nrows=2, ncols=2, width_ratios=[8,1], height_ratios=[1,8])
  8. ax1 = fig.add_subplot(spec[0, 0])
  9. ax1.hist(data[0], rwidth=0.9)
  10. ax1.axis('off')
  11. ax2 = fig.add_subplot(spec[1, 0])
  12. ax2.scatter(data[0], data[1])
  13. ax2.set_xlabel('my_data_x')
  14. ax2.set_ylabel('my_data_y')
  15. ax2.grid(True)
  16. ax3 = fig.add_subplot(spec[1, 1])
  17. ax3.hist(data[1], rwidth=0.9, orientation='horizontal')
  18. ax3.axis('off')
  19. fig.tight_layout()

image.png