python - Matplotlib 热图标签
问题描述
您好,感谢您的帮助!(下面提供的代码和数据)(下图的图像)
我正在尝试在此热图中添加一个图例,以解释地图上颜色的差异(较暖的颜色意味着较高的温度)。我要补充:
ax1.legend([ax1], ['Temp'])
问题是这行代码不会导致我的情节包含图例。我需要做什么才能添加解释温度和颜色之间关系的图例?
raw_data = pd.read_csv('https://raw.githubusercontent.com/the-
datadudes/deepSoilTemperature/master/allStationsDailyAirTemp1.csv', index_col=1, parse_dates=True)
df_all_stations = raw_data.copy()
# load the data into a DataFrame, not a Series
# parse the dates, and set them as the index
df1 = df_all_stations[df_all_stations['Station'] == 'Williston']
# groupby year and aggregate Temp into a list
dfg1 = df1.groupby(df1.index.year).agg({'Temp': list})
# create a wide format dataframe with all the temp data expanded
df1_wide = pd.DataFrame(dfg1.Temp.tolist(), index=dfg1.index)
# adding the data between 1990/01/01 -/04/23 and delete the 29th of Feb
rng = pd.date_range(start='1990-01-01', end='1990-04-23', freq='D')
df = pd.DataFrame(index= rng)
df.index = pd.to_datetime(df.index)
df['Temp'] = np.NaN
frames = [df, df1]
result = pd.concat(frames)
result = result[~((result.index.month == 2) & (result.index.day == 29))]
dfg1 = result.groupby(result.index.year).agg({'Temp': list})
df1_wide = pd.DataFrame(dfg1['Temp'].tolist(), index=dfg1.index)
# Setting all leftover empty fields to the average of that time in order to fill in the gaps
df1_wide = df1_wide.apply(lambda x: x.fillna(x.mean()),axis=0)
# ploting the data
fig, (ax1) = plt.subplots(ncols=1, figsize=(20, 5))
##ax1.set_title('Average Daily Air Temperature - Minot Station')
ax1.set_xlabel('Day of the year')
ax1.set_ylabel('Year of collected data')
ax1.legend([ax1], ['Temp'])
ax1.matshow(df1_wide, interpolation=None, aspect='auto');
解决方案
你要求的是colorbar
:
fig, (ax1) = plt.subplots(ncols=1, figsize=(20, 5))
##ax1.set_title('Average Daily Air Temperature - Minot Station')
ax1.set_xlabel('Day of the year')
ax1.set_ylabel('Year of collected data')
# register a colorbar mappable
cbm = ax1.matshow(df1_wide, interpolation=None, aspect='auto');
# plot the colorbar
cb = plt.colorbar(cbm, ax=ax1)
cb.set_label('My Color Map')
输出:
推荐阅读
- c++ - C++:我的简单计算器程序不会打印出来。我也认为我的变量命名不正确
- php - 无法通过 ajax 请求传递变量
- python - 如何为特定类型添加检查
- c# - C# 注册表写入不再有效
- angular - Angular angulartics2(谷歌分析)不会更新路线更改页面
- javascript - 如何使用 javascript 获取通过 SAM 创建的 AWS API 网关的端点
- bootstrap-4 - 是否可以使用一个徽标制作 2 个导航栏并在两个栏上左右对齐?
- sql-server - 春季启动时SQL Sever初始加载失败
- flask-session - 有人可以告诉我为什么会话不起作用
- java - 如何在 Java 中淡化 .wav 文件?