python爬取天气可视化代码
时间: 2023-10-09 14:08:48 浏览: 107
您好,以下是爬取天气数据并进行可视化的Python代码:
```python
import requests
import json
import pandas as pd
import matplotlib.pyplot as plt
# 获取天气数据
def get_weather(city):
url = f'https://free-api.heweather.net/s6/weather/forecast?location={city}&key=yourkey'
r = requests.get(url)
data = json.loads(r.text)
weather_data_list = data['HeWeather6'][0]['daily_forecast']
return weather_data_list
# 可视化天气数据
def visualize_weather(city, weather_data_list):
dates = [data['date'] for data in weather_data_list]
temps_max = [int(data['tmp_max']) for data in weather_data_list]
temps_min = [int(data['tmp_min']) for data in weather_data_list]
df = pd.DataFrame({'temps_max': temps_max, 'temps_min': temps_min}, index=dates)
ax = df.plot(kind='bar', color=['r', 'b'], rot=0)
ax.set_title(f'{city}天气预报')
ax.set_xlabel('日期')
ax.set_ylabel('温度(℃)')
plt.show()
if __name__ == '__main__':
city = '北京'
weather_data_list = get_weather(city)
visualize_weather(city, weather_data_list)
```
需要替换代码中的`yourkey`为自己的和风天气apikey。
阅读全文
相关推荐















