Python 提取 Excel 时间风速数据并绘制折线图
可以使用 pandas 和 matplotlib 库来实现这个任务。
首先,需要安装并导入这两个库:
import pandas as pd
import matplotlib.pyplot as plt
假设 Excel 文件名为'wind_data.xlsx',其中第一列为时间,第二列为风速。可以使用 pandas 的 read_excel 函数读取数据:
df = pd.read_excel('wind_data.xlsx', names=['time', 'wind_speed'])
这里将列名设置为'time' 和 'wind_speed',方便后续操作。
接下来,需要将时间列转换为 datetime 格式,并设置为索引:
df['time'] = pd.to_datetime(df['time'], format='%Y%m%d%H%M')
df.set_index('time', inplace=True)
这里使用了 to_datetime 函数将字符串格式的时间转换为 datetime 格式,format 参数指定了时间的格式。然后使用 set_index 函数将时间列设置为索引。
最后,可以使用 Matplotlib 绘制折线图:
plt.plot(df['wind_speed'].resample('1H').mean())
plt.xticks(df.index, df.index.strftime('%m-%d'), rotation=45)
plt.xlabel('Time')
plt.ylabel('Wind Speed (m/s)')
plt.title('Wind Speed over Time')
plt.show()
这里使用了 resample 函数将数据按小时重新采样,并计算每个小时的平均风速。然后使用 plot 函数绘制折线图。使用 xticks 函数设置 x 轴刻度为日期格式,并设置刻度标签的格式和角度。使用 xlabel 和 ylabel 函数设置坐标轴标签,使用 title 函数设置标题。最后使用 show 函数显示图像。
完整代码如下:
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_excel('wind_data.xlsx', names=['time', 'wind_speed'])
df['time'] = pd.to_datetime(df['time'], format='%Y%m%d%H%M')
df.set_index('time', inplace=True)
plt.plot(df['wind_speed'].resample('1H').mean())
plt.xticks(df.index, df.index.strftime('%m-%d'), rotation=45)
plt.xlabel('Time')
plt.ylabel('Wind Speed (m/s)')
plt.title('Wind Speed over Time')
plt.show()
原文地址: https://www.cveoy.top/t/topic/mQ2k 著作权归作者所有。请勿转载和采集!