Python气象绘图总结第一弹:基础图形绘制及设置,附官方文档总结
文章目录
前言
小磨叽终于开坑整理接触python这三四年以来的小技巧!这个系列将会包括折线图、柱状图、散点图、箱式图等,含底图的等值线图,还包括了横纵坐标轴、图例设置,时间格式处理,还有多子图!有必要说明的是,尽管参考各种博客文章很方便易懂,但是官方文档才是能够深入理解和掌握的唯一途径,一定要多看官方文档!!!(放这里了https://matplotlib.org/stable/gallery/index.html)
一、折线图
折线图往往是反应时间序列数据的第一选择,以展现数据背后的趋势。通常折线图的横坐标指代日期数据,纵坐标代表某个数值型变量。接下来将运用matplotlib和pandas模块进行绘制。
官方参考:https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.plot.html
读取2024年1月-2月(不完全)的气象数据并绘制时序图
# 导入库包
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib as mpl
import matplotlib.ticker as mtick
# 全局设置普通字体、数学字体、字号、刻度向内
mpl.rcParams['font.family'] = ['Times New Roman', 'Simsun']
mpl.rcParams['mathtext.fontset'] = 'stix'
mpl.rcParams['font.size'] = '12'
mpl.rcParams['xtick.direction'] = 'in'
mpl.rcParams['ytick.direction'] = 'in'
# 读取数据
data = pd.read_csv(r"E:\CSDN\561870-99999-2024.csv")
# 时间处理
data['date'] = data['Year'].map(str)+"/"+data['Month'].map(str)+"/"+data['Day'].map(str)
pd.to_datetime(data['date']) # 年+月+日=date,合并转换格式为time
data['date_time'] = pd.to_datetime(data['date']) + pd.TimedeltaIndex(data['Hour'],unit='H') # date+Hour=date_time,将小时数据设为时间索引并合并
data=data.drop(['date'],axis=1) # 删除不全的过渡列date
# 绘制温度T是时序图
fig = plt.figure(figsize=(8, 6), dpi=600)
plt.plot(data['date_time'], data['T'], lw = 2, color = 'steelblue', label = 'T')
ax = plt.gca() # 获取图的坐标信息
date_format = mpl.dates.DateFormatter("%m-%d") # 设置日期的显示格式
ax.xaxis.set_major_formatter(date_format)
xlocator = mpl.ticker.MultipleLocator(7) # 设置x轴每个刻度的间隔天数
ax.xaxis.set_major_locator(xlocator)
plt.xticks(rotation=45) # 为了避免x轴刻度标签的紧凑,将刻度标签旋转45度
# 绘制温度T和露点温度TD双y轴时序图
fig = plt.figure(figsize=(8, 6), dpi=600)
ax1 = fig.add_subplot(111)
lns1 = ax1.plot(data['date_time'], data['T'], marker='o', color='b', lw=1.5, label='T')
ax1.set_ylabel('T / $^{o}$C') # 上标
ax2 = ax1.twinx()
lns2 = ax2.plot(data['date_time'], data['TD'], marker='*', color='r', lw=1.5, label='TD')
ax2.set_ylabel(' TD / $^{o}$C')
ax2.set_xlabel('Same')
ax1.set_ylim(-5,25)
ax2.set_ylim(-10,10)
ax2.yaxis.set_major_formatter(mtick.FormatStrFormatter('%.0f')) # 保留0位小数
ax = plt.gca()
date_format = mpl.dates.DateFormatter("%m-%d")
ax.xaxis.set_major_formatter(date_format)
xlocator = mpl.ticker.MultipleLocator(7)
ax.xaxis.set_major_locator(xlocator)
# 图例控制
lns = lns1 + lns2
labs = [l.get_label() for l in lns]
ax1.legend(lns, labs, loc=3, ncol=2, fontsize=12)
plt.savefig('E:/CSDN/T_TD.png',dpi=600, bbox_inches='tight')
plt.show()
二、柱状图
柱状图是一种用矩形柱来表示数据分类的图表,可以呈现为垂直或水平方向,显示了不同类别之间的比较关系。对于垂直方向的柱状图,其高度与相应的数值成正比关系,水平轴 X 指定被比较的类别,垂直轴 Y 则表示具体的类别值。
官方参考:https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.bar.html
读取2024年1月7日-8日的气象数据并绘制柱状图
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
# 全局设置普通字体、数学字体、字号、刻度向内
mpl.rcParams['font.family'] = ['Times New Roman', 'Simsun']
mpl.rcParams['mathtext.fontset'] = 'stix'
mpl.rcParams['font.size'] = '12'
mpl.rcParams['xtick.direction'] = 'in'
mpl.rcParams['ytick.direction'] = 'in'
# 读取数据
data = pd.read_csv(r"E:\CSDN\561870-99999-2024.csv")
# 时间处理
data['date'] = data['Year'].map(str)+"/"+data['Month'].map(str)+"/"+data['Day'].map(str)
pd.to_datetime(data['date'])
data['date_time'] = pd.to_datetime(data['date']) + pd.TimedeltaIndex(data['Hour'],unit='H')
data=data.drop(['date'],axis=1)
data.set_index('date_time',inplace=True) # 设置索引
df = data.loc['2024-01-07':'2024-01-08'] # 提取2024年1月7日-8日
# 绘制温度T和露点温度TD的双柱状图
x = np.arange(len(df.index))
width = 0.3
T = x
TD = x + width
fig = plt.figure(figsize=(8, 6), dpi=600)
plt.bar(T,df['T'],width=width,color="b", label='T')
plt.bar(TD,df['TD'],width=width,color="r", label='TD')
ax = plt.gca()
date_format = mpl.dates.DateFormatter("%d-%H") #DateFormatter('%Y-%m-%d')年-月-日; DateFormatter('%d')显示日;DateFormatter('%H')显示小时
ax.xaxis.set_major_formatter(date_format)
# 柱状顶端标数字
for i in range(len(x)):
plt.text(T[i], df['T'][i],df['T'][i],va="bottom",ha="center",fontsize=8)
plt.text(TD[i], df['TD'][i],df['TD'][i],va="bottom",ha="center",fontsize=8)
plt.legend()
plt.xticks(rotation=45)
plt.savefig('E:/CSDN/bar_T_TD.png',dpi=600, bbox_inches='tight')
plt.show()
三、散点图
散点图用于发现两个数值变量之间的关系。如果需要研究两个数值型变量之间是否存在某种关系,例如正向的线性关系,或者是趋势性的非线性关系,那么散点图将是最佳的选择。
官方参考:https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.scatter.html
续上节绘制散点图
fig = plt.figure(figsize=(4, 3), dpi=600)
plt.scatter(df['T'], df['TD'], s=20, c='r', marker='o',)
plt.xlabel('T')
plt.ylabel('TD')
plt.savefig('E:/CSDN/scatter_T_TD.png',dpi=600, bbox_inches='tight')
plt.show()
四、箱式图
箱式图可以作为一种检测异常值的方法,或者用于多组数据的图形汇总,便于对各组数据进行直观比较分析。其包含的五数概括包括五数概括法(1)最小值(Q1-1.5IQR);(2)第一四分位数(Q1);(3)中位数(Q2);(4)第三四分位数(Q3);(5)最大值(Q3+1.5IQR)。
官方参考:https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.boxplot.html
续上节绘制箱式图
ax = plt.subplot()
ax.boxplot([df['T'], df['TD']])
ax.set_xlabel('Variabilies')
ax.set_xticklabels(['T', 'TD'])
ax.set_ylabel('degree')
plt.savefig('E:/CSDN/box_T_TD.png',dpi=600, bbox_inches='tight')
plt.show()
五、一张图上多个要素
续上节绘制折线叠加柱状图
fig = plt.figure(figsize=(8, 6), dpi=600)
plt.plot(df['T'], marker='o', color='b', lw=1.5, label='T')
plt.bar(df.index, df['T'], width=0.1)
plt.ylim(0,20)
plt.ylabel('T / $^{o}$C')
ax = plt.gca()
date_format = mpl.dates.DateFormatter("%d-%H")
ax.xaxis.set_major_formatter(date_format)
plt.savefig('E:/CSDN/multi_T_TD.png',dpi=600, bbox_inches='tight')
plt.show()
六、多子图
官方参考:https://matplotlib.org/stable/gallery/subplots_axes_and_figures/index.html
续上节绘制折线图、柱状图、散点图、箱式图
fig, axes = plt.subplots(2, 2, figsize=(14,8), dpi=600)
plt.subplots_adjust(hspace = 0.3, wspace = 0.15)
ax = plt.gca()
date_format = mpl.dates.DateFormatter("%d-%H")
ax1 = axes[0,0]
ax1.plot(df['T'], marker='o', color='b', lw=1.5, label='T')
ax1.xaxis.set_major_formatter(date_format)
ax1.set_xlabel('Time')
ax1.set_ylabel('T / $^{o}C$')
ax2 = axes[0,1]
ax2.bar(df.index, df['T'], width=0.1)
ax2.xaxis.set_major_formatter(date_format)
ax2.set_xlabel('Time')
ax2.set_ylabel('T / $^{o}C$')
ax3 = axes[1,0]
ax3.scatter(df['T'], df['TD'], s=20, c='r', marker='o')
ax3.set_xlabel('T / $^{o}C$')
ax3.set_ylabel('TD / $^{o}C$')
ax4 = axes[1,1]
ax4.boxplot([df['T'], df['TD']])
ax4.set_xlabel('Variabilies')
ax4.set_xticklabels(['T', 'TD'])
ax4.set_ylabel('$^{o}C$')
plt.savefig('E:/CSDN/subplots.png',dpi=600, bbox_inches='tight')
plt.show()
七、附整理常用设置官方文档
colors: https://matplotlib.org/stable/gallery/color/named_colors.html
colormap: https://matplotlib.org/stable/gallery/color/colormap_reference.html
marker: https://matplotlib.org/stable/gallery/lines_bars_and_markers/marker_reference.html
linestyles: https://matplotlib.org/stable/gallery/lines_bars_and_markers/linestyles.html
ticks: https://matplotlib.org/stable/gallery/ticks/index.html
总结
一文掌握气象领域常用的折线图、柱状图、散点图、箱式图,以及横纵坐标轴、图例设置,时间格式处理,还有多子图!惰性使然还有很多不完美之处,例如颜色、标题标签、是否斜体等等设置。第一次的总结记录就到这里啦,祝论文多多!
作者:青瓜呱呱呱