python3使用matplotlib繪製條形圖
阿新 • • 發佈:2018-12-24
繪製豎狀條形圖
- 程式碼
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()
- 效果圖