import csv import matplotlib.pyplot as plt from datetime import datetime # 解决中文显示问题 plt.style.use('seaborn') plt.rcParams['font.sans-serif'] = ['KaiTi'] # 指定默认字体 plt.rcParams['axes.unicode_minus'] = False # 解决保存图像是负号'-'显示为方块的问题 filename = 'data/sitka_weather_2018_simple.csv' with open(filename) as f: reader = csv.reader(f) # 创建一个与该文件相关联的阅读器对象 header_row = next(reader) # 读取文件头 dates, highs, lows = [], [], [] for row in reader: # 转换日期格式 current_date = datetime.strptime(row[2], '%Y-%m-%d') high = int(row[5]) low = int(row[6]) dates.append(current_date) highs.append(high) lows.append(low) fig, ax = plt.subplots() ax.plot(dates, highs, c='red', alpha=0.5) ax.plot(dates, lows, c='blue', alpha=0.5) ax.fill_between(dates, highs, lows, facecolor='blue', alpha=0.1) ax.set_title('2018年每日最高温度', fontsize=24) ax.set_xlabel('', fontsize=16) fig.autofmt_xdate() ax.set_ylabel('温度(F)', fontsize=16) ax.tick_params(axis='both', which='major', labelsize=16) plt.show()增加平均值显示
时间: 2024-01-24 10:05:25 浏览: 78
Matplotlib.pyplot 三维绘图的实现示例
要在图表中添加平均温度,可以在读取CSV文件并计算最高温度和最低温度后,再计算平均温度,并将其添加到图表中。
以下是示例代码:
```python
import csv
import matplotlib.pyplot as plt
from datetime import datetime
plt.style.use('seaborn')
plt.rcParams['font.sans-serif'] = ['KaiTi']
plt.rcParams['axes.unicode_minus'] = False
filename = 'data/sitka_weather_2018_simple.csv'
with open(filename) as f:
reader = csv.reader(f)
header_row = next(reader)
dates, highs, lows = [], [], []
for row in reader:
current_date = datetime.strptime(row[2], '%Y-%m-%d')
high = int(row[5])
low = int(row[6])
dates.append(current_date)
highs.append(high)
lows.append(low)
# 计算平均温度
avg = [(high + low) / 2 for high, low in zip(highs, lows)]
fig, ax = plt.subplots()
ax.plot(dates, highs, c='red', alpha=0.5)
ax.plot(dates, lows, c='blue', alpha=0.5)
ax.plot(dates, avg, c='green', alpha=0.5)
ax.fill_between(dates, highs, lows, facecolor='blue', alpha=0.1)
ax.set_title('2018年每日温度', fontsize=24)
ax.set_xlabel('', fontsize=16)
fig.autofmt_xdate()
ax.set_ylabel('温度(F)', fontsize=16)
ax.tick_params(axis='both', which='major', labelsize=16)
# 在图表中添加平均温度
avg_temp = sum(avg) / len(avg)
ax.text(dates[0], avg_temp, f'平均温度: {avg_temp:.1f}F', fontsize=12)
plt.show()
```
在这个版本的代码中,我们计算了平均温度,并使用`ax.plot(dates, avg, c='green', alpha=0.5)`在图表中添加了平均温度的折线。我们还使用`avg_temp = sum(avg) / len(avg)`计算了平均温度的值,并使用`ax.text(dates[0], avg_temp, f'平均温度: {avg_temp:.1f}F', fontsize=12)`将其添加到图表中。
阅读全文