读取 Excel 文件 pollution_us_Houston_2007_2009_O3.xlsx、pollution_us_NewYork_2007_2009_O3.xlsx.、pollution_us_Washington_2007_2009_O3.xlsx,利用matplotlib库,可视化对比显示3个城市2007~2009年O3Mean、O3AQI、O31st Max Hour的值,要求三幅图的名称分别为Houston_NewYork_Washington_2007_2009_O3Mean、Houston_NewYork_Washington_2007_2009_O3AQI、Houston_NewYork_Washington_2007_2009_O3lstMaxHour,包括图例,x轴刻度以"年—月"显示(为显示美观,请倾斜90度显示), y 轴显示刻度值,每幅图中三条曲线颜色分别为红色、绿色、蓝色。
时间: 2023-08-10 15:08:55 浏览: 116
读取Excel的实例
以下是实现代码:
```python
import pandas as pd
import matplotlib.pyplot as plt
# 读取数据
houston = pd.read_excel('pollution_us_Houston_2007_2009_O3.xlsx')
new_york = pd.read_excel('pollution_us_NewYork_2007_2009_O3.xlsx')
washington = pd.read_excel('pollution_us_Washington_2007_2009_O3.xlsx')
# 设置 x 轴刻度为年-月格式并倾斜 90 度
def format_x_axis_date(ax):
ax.xaxis.set_major_formatter(plt.FuncFormatter(lambda x, _: pd.to_datetime(x, unit='D').strftime('%Y-%m')))
plt.xticks(rotation=90)
# 绘制 O3Mean 图
fig, ax = plt.subplots()
ax.plot(houston['Date Local'], houston['O3Mean'], color='red', label='Houston')
ax.plot(new_york['Date Local'], new_york['O3Mean'], color='green', label='New York')
ax.plot(washington['Date Local'], washington['O3Mean'], color='blue', label='Washington')
plt.title('Houston_NewYork_Washington_2007_2009_O3Mean')
plt.xlabel('Date')
plt.ylabel('O3Mean')
plt.legend()
format_x_axis_date(ax)
plt.show()
# 绘制 O3AQI 图
fig, ax = plt.subplots()
ax.plot(houston['Date Local'], houston['O3AQI'], color='red', label='Houston')
ax.plot(new_york['Date Local'], new_york['O3AQI'], color='green', label='New York')
ax.plot(washington['Date Local'], washington['O3AQI'], color='blue', label='Washington')
plt.title('Houston_NewYork_Washington_2007_2009_O3AQI')
plt.xlabel('Date')
plt.ylabel('O3AQI')
plt.legend()
format_x_axis_date(ax)
plt.show()
# 绘制 O31st Max Hour 图
fig, ax = plt.subplots()
ax.plot(houston['Date Local'], houston['O31st Max Hour'], color='red', label='Houston')
ax.plot(new_york['Date Local'], new_york['O31st Max Hour'], color='green', label='New York')
ax.plot(washington['Date Local'], washington['O31st Max Hour'], color='blue', label='Washington')
plt.title('Houston_NewYork_Washington_2007_2009_O31st Max Hour')
plt.xlabel('Date')
plt.ylabel('O31st Max Hour')
plt.legend()
format_x_axis_date(ax)
plt.show()
```
说明:
1. 首先使用 pandas 库读取 3 个城市的 O3 数据。
2. 接着定义一个函数 format_x_axis_date,用于将 x 轴刻度格式化为年-月格式并倾斜 90 度。
3. 然后分别绘制 3 幅图,每幅图中分别绘制 3 条曲线,颜色分别为红色、绿色、蓝色,并加上图例。
4. 最后调用 format_x_axis_date 函数将 x 轴刻度格式化,并显示图像。
阅读全文