demo.py(绘制条形图,bar,barh):
# coding=utf-8
from matplotlib import pyplot as plt
from matplotlib import font_manager
# 设置中文字体
my_font = font_manager.FontProperties(fname="/usr/share/fonts/truetype/arphic/ukai.ttc")
x = ["战狼2","速度与激情8","功夫瑜伽","西游伏妖篇","变形金刚5:最后的骑士","摔跤吧!爸爸","加勒比海盗5:死无对证","金刚:骷髅岛","极限特工:终极回归","生化危机6:终章","乘风破浪","神偷奶爸3","智取威虎山","大闹天竺","金刚狼3:殊死一战","蜘蛛侠:英雄归来","悟空传","银河护卫队2","情圣","新木乃伊",]
y = [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=(18,10),dpi=80)
# 绘制条形图
plt.bar(range(len(x)), y, width=0.3) # width表示条形粗细
# 绘制条形图 (横向条形图)
# plt.barh(range(len(x)), y, height=0.3, color="orange") # 横向条形图中height表示条形粗细
# 设置x轴刻度
plt.xticks(range(len(x)), x, fontproperties=my_font, rotation=90)
# plt.yticks(range(len(x)), x, fontproperties=my_font) # barh()绘制横向条形图时,设置的是y轴刻度
# 保存图片
# plt.savefig("./movie.png")
plt.show()
demo.py(绘制多个条形图):
# coding=utf-8
from matplotlib import pyplot as plt
from matplotlib import font_manager
# 设置中文字体
my_font = font_manager.FontProperties(fname="/System/Library/Fonts/Hiragino Sans GB.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.2
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日")
# 设置图例
plt.legend(prop=my_font)
# 设置x轴的刻度
plt.xticks(x_15, a, fontproperties=my_font)
plt.show()
bar绘制的条形图如下:
barh绘制横向条形图如下:
绘制的多个条形图如下:
demo.py(用条形图模拟分布直方图):
# coding=utf-8
from matplotlib import pyplot as plt
interval = [0,5,10,15,20,25,30,35,40,45,60,90] # 区间的坐标
width = [5,5,5,5,5,5,5,5,5,15,30,60] # 区间大小(条形粗细)
quantity = [836,2737,3723,3926,3596,1438,3273,642,824,613,215,47]
print(len(interval),len(width),len(quantity)) # 12 12 12
# 设置图形大小
plt.figure(figsize=(20,8),dpi=80)
# 绘制条形图
plt.bar(interval,quantity,width=width) # width条形粗细(区间)可以是一个列表
# 设置x轴的刻度
temp_d = [5]+ width[:-1]
_x = [i-temp_d[interval.index(i)]*0.5 for i in interval]
plt.xticks(_x,interval)
plt.grid(alpha=0.4) # 网格
plt.show()