柱狀圖圖繪制
效果如下:
電影數據如下圖所示:
1、繪制
- matplotlib.pyplot.bar(x, width, align='center', **kwargs)
Parameters: x : sequence of scalars. width : scalar or array-like, optional 柱狀圖的寬度 align : {‘center’, ‘edge’}, optional, default: ‘center’ Alignment of the bars to the x coordinates: ‘center’: Center the base on the x positions. ‘edge’: Align the left edges of the bars with the x positions. 每個柱狀圖的位置對齊方式 **kwargs : color:選擇柱狀圖的顏色 Returns: `.BarContainer` Container with all the bars and optionally errorbars.
代碼實現:
# 完成簡單的條形圖展現不同的電影票房之間的對比 plt.figure(figsize=(20, 8), dpi=80) # 准備電影的名字以及電影的票房數據 movie_name = ['雷神3:諸神黃昏','正義聯盟','東方快車謀殺案','尋夢環游記','全球風暴','降魔傳','追捕','七十七天','密戰','狂獸','其它'] y = [73853,57767,22354,15969,14839,8725,8716,8318,7916,6764,52222] # 放進橫坐標的數字列表 x = range(len(movie_name)) # 畫出條形圖 plt.bar(x, y, width=0.5, color=['b','r','g','y','c','m','y','k','c','g','g']) # 修改刻度名稱 plt.xticks(x, movie_name) plt.show()
3、比較相同天數的票房
# 三部電影的首日和首周票房對比 plt.figure(figsize=(20, 8), dpi=80) movie_name = ['雷神3:諸神黃昏','正義聯盟','尋夢環游記'] first_day = [10587.6,10062.5,1275.7] first_weekend=[36224.9,34479.6,11830] x = range(len(movie_name)) # 畫出柱狀圖 plt.bar(x, first_day, width=0.2, label="首日票房") # 首周柱狀圖顯示的位置在首日的位置右邊 plt.bar([i+0.2 for i in x], first_weekend, width=0.2, label="首周票房") # 顯示X軸中文,固定在首日和首周的中間位置 plt.xticks([i+0.1 for i in x], movie_name) plt.legend(loc='best') plt.show()