#任务要求
使用“豆瓣电影数据.xlsx”数据,完成以下任务:
1、绘制各国家电影数量条形图(按此命名工作表),要求为横向条形图,按照升序排列,条形图顶部要有标签(要全部显示);
2、创建电影评分的直方图(按此命名),数据间距为0.5分,修改底部数字标签,以实际评分区间为底部标签数值,标签要显示完整。
#各国家电影数量条形图
#matplotlib
1
2
3
|
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
|
1
2
|
df = pd.read_excel('data/豆瓣电影数据.xlsx', index_col=0)
df
|
1
2
|
height = df.value_counts('产地')
height
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
plt.figure(dpi=150)
plt.barh(height.index, height, color='salmon')
for x, y in enumerate(height.values):
# 前两个参数表示标签的坐标位置,第三个参数表示标签的值
# 为了使数据标签与矩形间隔相同,这里必须水平对齐为left
plt.text(y+50, x, y, fontsize=7, va='center', ha='left')
plt.xlabel('电影数量')
plt.xlim([0,13000])
plt.yticks(fontsize=6)
plt.title('各国家电影数量')
plt.savefig('img/hw11.png')
plt.show()
|

#seaborn
如果不用添加数据标签,seaborn一行代码其实就可以做出来的。但因为有作图要求,结果发现与直接用matplotlib相比做功反而更多。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
df = pd.read_excel('data/豆瓣电影数据.xlsx', index_col=0)
plt.figure(dpi=150)
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
sns.countplot(y='产地', data=df, \
order=df.value_counts('产地', ascending=True).index)
for x, y in enumerate(num.values):
plt.text(y+50, x, y, fontsize=7, va='center', ha='left')
plt.xlim([0,13000])
plt.yticks(fontsize=6)
plt.xlabel('电影数量')
plt.ylabel('')
plt.savefig('img/hw12.png')
plt.show()
|

#电影评分直方图
#matplotlib
1
2
3
|
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
|
1
2
|
df = pd.read_excel('data/豆瓣电影数据.xlsx', index_col=0)
df
|
bins分成[2, 2.5, 3, ..., 10]。
1
2
|
bins = [x/2 for x in range(4, 21)]
bins
|
要求为[2,2,4] [2.5,3]这种格式。
1
2
|
bins_name = [str(x/2)+'-'+str(x/2+0.4) for x in range(4, 20)]
bins_name
|
1
2
3
4
5
6
7
8
9
10
11
12
13
|
plt.figure(dpi=150)
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
plt.hist(df['评分'], bins=bins, align='left', rwidth=0.8, color='skyblue')
# align=left使得柱子往左移到对准刻度
# rwidth设置柱子间间隔
plt.xticks(bins[:-1], bins_name, rotation=45, fontsize=7)
# 用 bins_name 替换 [2,2.5,..., 9.5] 刻度
plt.title('电影评分直方图')
plt.ylabel('数量')
plt.savefig('img/hw13.png')
plt.show()
|
