matplotlib绘制条形图
Posted kmirror
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了matplotlib绘制条形图相关的知识,希望对你有一定的参考价值。
1. 普通条形图
import numpy as np import matplotlib.pyplot as plt from matplotlib import font_manager my_font = font_manager.FontProperties(fname=r‘C:/Windows/Fonts/simkai.ttf‘) # 设置字体 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] # 设置图形大小 fig = plt.figure(figsize=(16, 8), dpi=100) # 绘制条形图 plt.bar(a, b, width=0.3) # 设置字符串到x轴 plt.xticks(fontproperties=my_font, rotation=-45) plt.savefig(‘1.png‘) plt.show()
结果:
2. 横向条形图
# 绘制横着的条形图 import numpy as np import matplotlib.pyplot as plt from matplotlib import font_manager my_font = font_manager.FontProperties(fname=r‘C:/Windows/Fonts/simkai.ttf‘) # 设置字体 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] # 设置图形大小 fig = plt.figure(figsize=(16, 8), dpi=100) # 绘制横着的条形图 plt.barh(a, b, height=0.3, color=‘orange‘) # 宽度边高度 # 设置字符串到y轴 plt.yticks(fontproperties=my_font) plt.xticks(np.arange(60)) plt.grid(alpha=0.2) plt.savefig(‘2.png‘) plt.show()
3. 比较条形图
# 绘制比较条形图 import numpy as np import matplotlib.pyplot as plt from matplotlib import font_manager my_font = font_manager.FontProperties(fname=r‘C:/Windows/Fonts/simkai.ttf‘) # 设置字体 a = ["猩球崛起3:终极之战", "敦刻尔克", "蜘蛛侠:英雄归来", "战狼2"] b_16 = [15746, 312, 4497, 319] b_15 = [12357, 156, 2045, 168] b_14 = [2358, 399, 2358, 362] plt.figure(figsize=(16, 8), dpi=100) bar_width = 0.2 x = list(range(len(a))) plt.bar(x, b_14, width=bar_width, label=‘2017-09-14‘) plt.bar([i + bar_width for i in x], b_15, width=bar_width, label=‘2017-09-15‘) plt.bar([i + bar_width * 2 for i in x], b_16, width=bar_width, label=‘2017-09-16‘) plt.title(‘9月14,15,16三天票房情况‘, fontproperties=my_font) plt.xticks([i + bar_width for i in x], a, fontproperties=my_font) # 让下标位置定位到中间 plt.legend(prop=my_font) plt.savefig(‘3.png‘) plt.show()
以上是关于matplotlib绘制条形图的主要内容,如果未能解决你的问题,请参考以下文章
Python使用matplotlib绘制柱状图(bar plot)实战:水平条形图垂直条形图分组条形图堆叠条形图