地球的温度正在上升,没有什么比“变暖条纹”更简单、更易于理解的图形来展示这一点。由 Ed Hawkins 教授引入,它们展示了过去 170 年全球平均气温或您所在地区的温度,以从蓝色到红色的彩色条形表示,可在 #ShowYourStripes 网站查看。
此后,条纹已成为未来科学家的标志。以下是使用 Matplotlib 自己重现此图形的方法。
我们将使用由英国气象局发布的 HadCRUT4 数据集。它使用组合的海面和陆地表面温度。用于变暖条纹的数据集是年度全球平均值。
首先,让我们导入我们将要使用的一切。该图将包含每个年份的条形,使用自定义颜色映射进行着色。
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
from matplotlib.collections import PatchCollection
from matplotlib.colors import ListedColormap
import pandas as pd
然后我们定义时间限制、中性颜色的参考周期以及最大饱和度的周围范围。
FIRST = 1850
LAST = 2018 # inclusive
# Reference period for the center of the color scale
FIRST_REFERENCE = 1971
LAST_REFERENCE = 2000
LIM = 0.7 # degrees
在这里,我们使用 pandas 读取固定宽度文本文件,仅读取前两列,即年份和 1961 年至 1990 年平均值的偏差。
# data from
# https://www.metoffice.gov.uk/hadobs/hadcrut4/data/current/time_series/HadCRUT.4.6.0.0.annual_ns_avg.txt
df = pd.read_fwf(
"HadCRUT.4.6.0.0.annual_ns_avg.txt",
index_col=0,
usecols=(0, 1),
names=["year", "anomaly"],
header=None,
)
anomaly = df.loc[FIRST:LAST, "anomaly"].dropna()
reference = anomaly.loc[FIRST_REFERENCE:LAST_REFERENCE].mean()
这是我们的自定义颜色映射,我们也可以使用 matplotlib 附带的颜色映射之一,例如 coolwarm
或 RdBu
。
# the colors in this colormap come from http://colorbrewer2.org
# the 8 more saturated colors from the 9 blues / 9 reds
cmap = ListedColormap(
[
"#08306b",
"#08519c",
"#2171b5",
"#4292c6",
"#6baed6",
"#9ecae1",
"#c6dbef",
"#deebf7",
"#fee0d2",
"#fcbba1",
"#fc9272",
"#fb6a4a",
"#ef3b2c",
"#cb181d",
"#a50f15",
"#67000d",
]
)
我们创建一个具有单个坐标轴对象的图形,该对象填充图形的整个区域并且没有任何坐标轴刻度或标签。
fig = plt.figure(figsize=(10, 1))
ax = fig.add_axes([0, 0, 1, 1])
ax.set_axis_off()
最后,我们为每一年创建条形,分配数据、颜色映射和颜色限制,并将其添加到坐标轴上。
# create a collection with a rectangle for each year
col = PatchCollection([Rectangle((y, 0), 1, 1) for y in range(FIRST, LAST + 1)])
# set data, colormap and color limits
col.set_array(anomaly)
col.set_cmap(cmap)
col.set_clim(reference - LIM, reference + LIM)
ax.add_collection(col)
确保坐标轴限制正确,然后保存图形。
ax.set_ylim(0, 1)
ax.set_xlim(FIRST, LAST + 1)
fig.savefig("warming-stripes.png")