Python代码对豆瓣top250电影评分变化趋势进行可视化
时间: 2023-06-24 12:08:57 浏览: 69
好的,需要用到Python的数据分析和可视化库,具体的步骤如下:
1. 导入必要的库:
```python
import pandas as pd
import matplotlib.pyplot as plt
```
2. 读取数据:
```python
df = pd.read_csv('douban_top250.csv', encoding='utf-8')
```
这里假设数据文件名为`douban_top250.csv`,并且使用了UTF-8编码。
3. 数据预处理:
```python
df['year'] = df['release_date'].apply(lambda x: int(x.split('-')[0]))
df['month'] = df['release_date'].apply(lambda x: int(x.split('-')[1]))
df['day'] = df['release_date'].apply(lambda x: int(x.split('-')[2]))
df['release_date'] = pd.to_datetime(df[['year', 'month', 'day']])
```
这里将电影的上映日期拆分成年、月、日三个字段,并转换成标准的日期格式。
4. 计算每部电影的评分变化:
```python
df['score_change'] = df.groupby('title')['score'].apply(lambda x: x.diff())
```
这里使用了pandas的`groupby`函数按电影名称分组,然后对每个分组计算评分变化。
5. 绘制折线图:
```python
plt.figure(figsize=(12, 6))
for title, group in df.groupby('title'):
plt.plot(group['release_date'], group['score'], label=title)
plt.legend()
plt.xlabel('Release Date')
plt.ylabel('Score')
plt.title('Douban Top250 Movie Ratings Trend')
plt.show()
```
这里使用了matplotlib库绘制折线图,图像大小为12x6,循环遍历每个电影并绘制对应的评分变化曲线,添加图例、坐标轴标签和标题,并展示图像。
完整代码如下:
```python
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv('douban_top250.csv', encoding='utf-8')
df['year'] = df['release_date'].apply(lambda x: int(x.split('-')[0]))
df['month'] = df['release_date'].apply(lambda x: int(x.split('-')[1]))
df['day'] = df['release_date'].apply(lambda x: int(x.split('-')[2]))
df['release_date'] = pd.to_datetime(df[['year', 'month', 'day']])
df['score_change'] = df.groupby('title')['score'].apply(lambda x: x.diff())
plt.figure(figsize=(12, 6))
for title, group in df.groupby('title'):
plt.plot(group['release_date'], group['score'], label=title)
plt.legend()
plt.xlabel('Release Date')
plt.ylabel('Score')
plt.title('Douban Top250 Movie Ratings Trend')
plt.show()
```
运行代码后,即可生成豆瓣top250电影评分变化趋势的折线图。