本文实例为大家分享了python3使用matplotlib绘制条形图的具体代码,供大家参考,具体内容如下
绘制竖状条形图
代码
from matplotlib import pyplot as plt from matplotlib import font_manager my_font = font_manager.FontProperties(fname="/usr/share/fonts/truetype/arphic/ukai.ttc") a = ["战狼2", "速度与激情8", "功夫瑜伽", "西游伏妖篇", "变形金刚5:最后的骑士", "摔跤吧!爸爸", "加勒比海盗5:死无对证", "金刚:骷髅岛", "极限特工:终极回归", "生化危机6:终章", "乘风破浪", "神偷奶爸3", "智取威虎山", "大闹天竺", "金刚狼3:殊死一战", "蜘蛛侠:英雄归来", "悟空传", "银河护卫队2", "情圣", "新木乃伊", ] b = [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] plt.figure(figsize=(15,7)) # 绘制条形图 plt.bar(range(len(a)),b,width=0.3) # 对应x轴与字符串 plt.xticks(range(len(a)),a,fontproperties=my_font,rotation=90) plt.savefig("./bar1.png") plt.show()
效果图
绘制横状条形图
代码
# 绘制横着的条形图 from matplotlib import pyplot as plt from matplotlib import font_manager my_font = font_manager.FontProperties(fname="/usr/share/fonts/truetype/arphic/ukai.ttc") a = ["战狼2", "速度与激情8", "功夫瑜伽", "西游伏妖篇", "变形金刚5:最后的骑士", "摔跤吧!爸爸", "加勒比海盗5:死无对证", "金刚:骷髅岛", "极限特工:终极回归", "生化危机6:终章", "乘风破浪", "神偷奶爸3", "智取威虎山", "大闹天竺", "金刚狼3:殊死一战", "蜘蛛侠:英雄归来", "悟空传", "银河护卫队2", "情圣", "新木乃伊", ] b = [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] plt.figure(figsize=(15, 7)) # 绘制条形图 plt.barh(range(len(a)), b, height=0.3,color='orange') # 对应x轴与字符串 plt.yticks(range(len(a)), a, fontproperties=my_font, rotation=0) # 添加网格 alpha参数是设置网格的透明度的 plt.grid(alpha=0.3) # 保存图片 plt.savefig("./bar1.png") plt.show()
效果图
需要注意的是横着的和竖着的条形图的区别在与横着的使用的是barh()方法,同时要注意它传参数的顺序是:
def barh(y, width, height=0.8, left=None, *, align='center', **kwargs):
绘制多次条形图
代码
from matplotlib import pyplot as plt from matplotlib import font_manager myfont = font_manager.FontProperties(fname="/usr/share/fonts/truetype/arphic/ukai.ttc") a = ["猩球崛起3:终极之战","敦刻尔克","蜘蛛侠:英雄归来","战狼2"] b_16 = [15746,312,4497,319] b_15 = [12357,156,2045,168] b_14 = [2358,399,2358,362] bar_width = 0.25 x_14 = list(range(len(a))) x_15 = list(i+bar_width for i in x_14) x_16 = list(i+bar_width for i in x_15) # 设置图形大小 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日") # 设置图例 plt.legend(prop=myfont) # 设置x轴刻度 plt.xticks(x_15,a,fontproperties=myfont) plt.savefig("./mutiy.png") plt.show()
效果图
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。