Matplotlib的使用——条形图

绘制单个条形图

  • 案例: 假设你获取到了某年内地电影票房前20的电影(列表a)和电影票房数据(列表b), 那么如何更加直观的展示该数据?
from matplotlib import pyplot as plt
from matplotlib import font_manager

myfont = font_manager.FontProperties(fname="/usr/share/fonts/cjkuni-uming/uming.ttc", size=18)
titlefont = font_manager.FontProperties(fname="/usr/share/fonts/cjkuni-uming/uming.ttc", size=24)

y_money = [56.01, 26.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]
x_movies = ["流浪地球%s" %(i) for i in range(len(y_money))]

plt.figure(figsize=(30, 10))

# 生成竖向的条形图
plt.bar(range(len(x_movies)), y_money, color='orange', width=0.5)
# 生成横向的条形图
# plt.barh(range(len(x_movies)), y_money, color='orange', height=0.7)

plt.xticks(range(len(y_money)), labels=x_movies, fontproperties=myfont, rotation=45)
# plt.yticks(range(len(y_money)), labels=x_movies, fontproperties=myfont, rotation=45)

plt.title("某年内地电影票房前20的电影和电影票房数据", fontproperties=titlefont)
plt.xlabel("电影名", fontproperties=myfont)
plt.ylabel("电影票房(单位:亿)", fontproperties=myfont)
plt.savefig('doc/bar.png')

绘制多个条形图

  • 案例: 假设你知道了列表a中电影分别在2017-09-14(b_14), 2017-09-15(b_15), 2017-09-16(b_16)三天的票房,为了展示列表中电影本身的票房以及同其他电影的数据对比情况,应该如何更加直观的呈现该数据?
from matplotlib import pyplot as plt
from matplotlib import font_manager

myfont = font_manager.FontProperties(fname="/usr/share/fonts/cjkuni-uming/uming.ttc", size=18)
titlefont = font_manager.FontProperties(fname="/usr/share/fonts/cjkuni-uming/uming.ttc", size=24)

x_movies_name = ["猩球崛起3:终极之战", "敦刻尔克", "蜘蛛侠:英雄归来", "战狼2"]
y_16 = [15746, 312, 4497, 319]
y_15 = [12357, 156, 2045, 168]
y_14 = [2358, 399, 2358, 362]

plt.figure(figsize=(30, 10))

bar_width = 0.3

x_range = range(len(x_movies_name))

plt.bar(x_range, y_14, color='green', width=bar_width, label="2017-09-14票房数据")
plt.bar([i + bar_width for i in x_range], y_15, color='red', width=bar_width, label="2017-09-15票房数据")
plt.bar([i + bar_width * 2 for i in x_range], y_16, color='orange', width=bar_width, label="2017-09-16票房数据")

plt.xticks(range(len(x_movies_name)), labels=x_movies_name, fontproperties=myfont, rotation=45)

plt.title("某年内地电影票房前20的电影和电影票房数据", fontproperties=titlefont)
plt.xlabel("电影名", fontproperties=myfont)
plt.ylabel("电影票房(单位:亿)", fontproperties=myfont)
plt.savefig('doc/bar.png')

你可能感兴趣的:(python)