【Python数据分析 - 2】:多个坐标系的绘制

文章目录

  • 多个坐标系绘制的代码
  • 绘图结果

多个坐标系绘制的代码

本文无过多讲解,大部分为代码,提供了解。

import matplotlib.pyplot as plt
import random

# 设置字体
plt.rcParams['font.sans-serif'] = ['SimHei']

# 创建fig和axes对象,nrow是行,ncol是列,这里表示设置一行二列的坐标系
fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(20, 8))
x = range(60)
y_shanghai = [random.uniform(15, 18) for i in x]
y_beijing = [random.uniform(1, 3) for i in x]

# 构造中文
x_ch = ['11点{}分'.format(i) for i in x]
y_ticks = range(40)

# plt是对整体的画图,axes是对每个坐标系进行处理
# axes[0]表示为第一个坐标系,0为索引值
axes[0].plot(x, y_shanghai, label='上海')
axes[1].plot(x, y_beijing, label='北京', linestyle='--', color='r')

# 修改x,y轴坐标的刻度显示,注意使用subplot方法创建的图表不能直接使用set_sticks方法传入自定义的刻度,必须使用set_sticklabels()方法
axes[0].set_xticklabels(x_ch[::5])
axes[1].set_xticklabels(x_ch[::5])
axes[0].set_yticks(y_ticks[::5])
axes[1].set_yticks(y_ticks[::5])

# 设置坐标轴名称、标头
axes[0].set_xlabel('时间')
axes[1].set_xlabel('时间')
axes[0].set_ylabel('温度')
axes[1].set_ylabel('温度')

axes[0].set_title('上海温度变化情况')
axes[1].set_title('北京温度变化情况')

axes[0].legend(loc='best')
axes[1].legend(loc='best')

# 展示绘图结果
plt.show()

绘图结果

【Python数据分析 - 2】:多个坐标系的绘制_第1张图片

你可能感兴趣的:(数据分析,python,数据分析,开发语言)