import requests import matplotlib.pyplot as plt import matplotlib.font_manager as fm from bs4 import BeautifulSoup # 发送HTTP请求,获取网页内容 url = 'http://www.weather.com.cn/weather/101260101.shtml' response = requests.get(url) content = response.text # 解析网页内容,提取天气数据 soup = BeautifulSoup(content, 'html.parser') weather_list = soup.find('ul', class_='t clearfix').find_all('li') dates = [] temperatures = [] for weather in weather_list: date = weather.find('h1').text.strip() temperature = weather.find('p', class_='tem').text.strip().replace('\n', '').replace(' ', '') dates.append(date) temperatures.append(temperature) # 数据可视化 plt.plot(dates, temperatures) plt.rcParams['font.sans-serif'] = ['SimSun', 'Arial'] plt.xlabel('日期') plt.ylabel('温度') plt.title('贵阳未来一周天气预报',fontname=['SimHei']) plt.xticks(rotation=45) plt.show()该代码得到的结果X轴出现字符乱码,如何解决。
时间: 2023-09-07 17:12:20 浏览: 111
python常用库(带源码、详细解释、效果图!!!pandas、Matplotlib、爬虫相关的request库和bs4等。)
你可以尝试使用以下代码解决X轴字符乱码的问题:
```python
import requests
import matplotlib.pyplot as plt
import matplotlib.font_manager as fm
from bs4 import BeautifulSoup
# 发送HTTP请求,获取网页内容
url = 'http://www.weather.com.cn/weather/101260101.shtml'
response = requests.get(url)
content = response.text
# 解析网页内容,提取天气数据
soup = BeautifulSoup(content, 'html.parser')
weather_list = soup.find('ul', class_='t clearfix').find_all('li')
dates = []
temperatures = []
for weather in weather_list:
date = weather.find('h1').text.strip()
temperature = weather.find('p', class_='tem').text.strip().replace('\n', '').replace(' ', '')
dates.append(date)
temperatures.append(temperature)
# 数据可视化
plt.plot(dates, temperatures)
plt.rcParams['font.sans-serif'] = ['SimSun', 'Arial']
plt.xlabel('日期', fontproperties='SimHei') # 设置X轴标签字体为宋体
plt.ylabel('温度', fontproperties='SimHei') # 设置Y轴标签字体为宋体
plt.title('贵阳未来一周天气预报', fontproperties='SimHei') # 设置标题字体为宋体
plt.xticks(rotation=45)
plt.show()
```
上述代码中,我添加了 `fontproperties` 参数来设置X轴标签、Y轴标签和标题的字体为宋体(SimHei)。这样可以解决X轴字符乱码的问题。
阅读全文