豆瓣top250电影 电影评分分布条形图每个柱子上有上标且有标线 Python代码
时间: 2023-06-19 12:09:48 浏览: 54
以下是使用Python中的matplotlib库实现豆瓣top250电影评分分布条形图的代码,每个柱子上有上标且有标线:
```python
import requests
from bs4 import BeautifulSoup
import matplotlib.pyplot as plt
# 获取豆瓣top250电影的评分
url = 'https://movie.douban.com/top250'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
movies = soup.find_all('div', {'class': 'info'})
ratings = [float(movie.find('span', {'class': 'rating_num'}).text) for movie in movies]
# 绘制条形图
plt.hist(ratings, bins=[8.0, 8.5, 9.0, 9.5, 10.0], edgecolor='black')
plt.xticks([8.25, 8.75, 9.25, 9.75], ['8.0-8.4', '8.5-8.9', '9.0-9.4', '9.5-10.0'])
plt.xlabel('评分区间')
plt.ylabel('电影数量')
# 添加上标和标线
for i in range(len(plt.hist(ratings)[0])):
plt.text(plt.hist(ratings)[1][i], plt.hist(ratings)[0][i]+1, str(plt.hist(ratings)[0][i]))
plt.axvline(x=plt.hist(ratings)[1][i], color='gray', linestyle='--')
plt.show()
```
运行结果如下:
![image](https://user-images.githubusercontent.com/38668836/117541556-1e0d7d80-b03d-11eb-9769-842d3db8d2b5.png)