本节目标:绘制横着放的条形图
绘制竖着放的条形图
在同一图中,绘制多次条形图做对比
练习1
假设你获取到了2017年内地电影票房前20的电影(列表a)和电影票房数据(列表b),那么如何更加直观的展示该数据?
a=["战狼","速度与激情","功夫瑜伽","西游伏魔篇","变形金刚","最后的骑士","摔跤吧,爸爸","加勒比海盗5","死无对证","金刚:骷颅岛","极限特工","生化危机","乘风破浪","神偷奶爸","智取威虎山","大闹天宫","金刚狼","蜘蛛侠","悟空传","银河护卫队"]
b=[56.01,29.94,17.53,16.49,15.45,12.96,11.8,11.61,11.28,11.12,10.49,10.3,8.75,7.55,7.32,6.99,6.88,6.86,6.58,6.23],单位:亿
绘制横着的条形图:
from matplotlib import pyplot as plt
#设置中文显示
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei']
a=["战狼","速度与激情","功夫瑜伽","西游伏魔篇","变形金刚","最后的骑士","摔跤吧,爸爸","加勒比海盗5",
"死无对证","金刚:骷颅岛","极限特工","生化危机","乘风破浪","神偷奶爸", "智取威虎山","大闹天宫",
"金刚狼","蜘蛛侠","悟空传","银河护卫队"]
b=[56.01,29.94,17.53,16.49,15.45,12.96,11.8,11.61,11.28,11.12,10.49,10.3,8.75,7.55,7.32,6.99,6.88,
6.86,6.58,6.23]
#绘制图形大小
plt.figure(figsize=(20,8),dpi=80)
#绘制条形图
plt.barh(range(len(a)),b,height=0.5,color="orange")
#绘制坐标,用列表a中的内容替换刻度值
plt.yticks(range(len(a)),a)
#绘制网格
plt.grid(alpha=0.5)
#展示图形
plt.show()
结果:
绘制竖着的条形图:
from matplotlib import pyplot as plt
#设置中文显示
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei']
a=["战狼","速度与激情","功夫瑜伽","西游伏魔篇","变形金刚","最后的骑士","摔跤吧,爸爸","加勒比海盗5",
"死无对证","金刚:骷颅岛","极限特工","生化危机","乘风破浪","神偷奶爸", "智取威虎山","大闹天宫",
"金刚狼","蜘蛛侠","悟空传","银河护卫队"]
b=[56.01,29.94,17.53,16.49,15.45,12.96,11.8,11.61,11.28,11.12,10.49,10.3,8.75,7.55,7.32,6.99,6.88,
6.86,6.58,6.23]
#绘制图形大小
plt.figure(figsize=(20,15),dpi=80)
#绘制条形图
plt.bar(range(len(a)),b,width=0.5)
#绘制坐标,用列表a中的内容替换刻度值
plt.xticks(range(len(a)),a,rotation=45)
#展示图形
plt.show()
结果:
练习2
假设你知道了列表a中电影分别在2017-09-14(b_14),2017-09-15(b_15),2017-09-16(b_16)三天的票房,为了展示列表中电影本身的票房以及同其他电影的数据对比情况,应该如何更加直观的呈现该数据?
a=["猩球崛起3:终极之战","敦刻尔克","蜘蛛侠:英雄归来","战狼2"]
b_16=[15746,312,4497,319]
b_15=[12357,156,2045,168]
b_14=[2358,399,2358,362]
#绘制多次条形图
from matplotlib import pyplot as plt
#设置中文显示
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei']
a=["猩球崛起3:终极之战","敦刻尔克","蜘蛛侠:英雄归来","战狼2"]
b_16=[15746,312,4497,319]
b_15=[12357,156,2045,168]
b_14=[2358,399,2358,362]
#设置条形宽度
bar_width = 0.2
#设置各个条形图x轴范围
x_14 = list(range(len(a)))
x_15 = [i+bar_width for i in x_14]
x_16 = [i+bar_width *2 for i in x_14]
#设置图形大小
plt.figure(figsize=(20,8),dpi=80)
#画图
plt.bar(range(len(a)),b_14,width=bar_width,label="9月14日")
plt.bar(x_15,b_15,width=bar_width,label="9月15日")
plt.bar(x_16,b_16,width=bar_width,label="9月16日")
#设置x轴的刻度
#a用的值替换刻度,为了将刻度放在中间,所以用x_15
plt.xticks(x_15,a)
#设置图例
plt.legend()
#网格
plt.grid(alpha=0.5)
#展示
plt.show()
结果: