目录html
今天咱们学习的是条形图,导入的函数是:python
plt.bar() 于 plt.barh算法
原函数定义:api
bar
(x, height, width=0.8, bottom=None, , align='center', data=None, kwargs*)函数
具体参考:官网说明文档学习
参数 | 说明 | 类型 |
---|---|---|
x | x坐标 | int,float |
height | 条形的高度 | int,float |
width | 宽度 | 0~1,默认0.8 |
botton | 条形的起始位置 | 也是y轴的起始坐标 |
align | 条形的中心位置 | “center”,"lege"边缘 |
color | 条形的颜色 | “r","b","g","#123465",默认“b" |
edgecolor | 边框的颜色 | 同上 |
linewidth | 边框的宽度 | 像素,默认无,int |
tick_label | 下标的标签 | 能够是元组类型的字符组合 |
log | y轴使用科学计算法表示 | bool |
orientation | 是竖直条仍是水平条 | 竖直:"vertical",水平条:"horizontal" |
""" 默认的是竖值条形图 """ import numpy as np import matplotlib.pyplot as plt import matplotlib # 将全局的字体设置为黑体 matplotlib.rcParams['font.family'] = 'SimHei' # 数据 N = 5 y = [20, 10, 30, 25, 15] x = np.arange(N) # 绘图 x x轴, height 高度, 默认:color="blue", width=0.8 p1 = plt.bar(x, height=y, width=0.5, ) # 展现图形 plt.show()
须要把:orientation="horizontal",而后x,与y的数据交换,再添加bottom=x,便可。字体
""" 水平条形图,须要修改如下属性 orientation="horizontal" """ import numpy as np import matplotlib.pyplot as plt # 数据 N = 5 x = [20, 10, 30, 25, 15] y = np.arange(N) # 绘图 x= 起始位置, bottom= 水平条的底部(左侧), y轴, height 水平条的宽度, width 水平条的长度 p1 = plt.bar(x=0, bottom=y, height=0.5, width=x, orientation="horizontal") # 展现图形 plt.show()
具体可参考:官网说明文档code
使用barh()时,bottom改成left, 而后宽变高,高变宽。htm
""" 水平条形图,须要如下属性 orientation="horizontal" """ import numpy as np import matplotlib.pyplot as plt # 数据 N = 5 x = [20, 10, 30, 25, 15] y = np.arange(N) # 绘图 y= y轴, left= 水平条的底部, height 水平条的宽度, width 水平条的长度 p1 = plt.barh(y, left=0, height=0.5, width=x) # 展现图形 plt.show()
[图片上传失败...(image-c414f2-1552186154190)]blog
咱们再同一张画布,画两组条形图,而且紧挨着就时并列条形图。
改变x的位置。
import numpy as np import matplotlib.pyplot as plt # 数据 x = np.arange(4) Bj = [52, 55, 63, 53] Sh = [44, 66, 55, 41] bar_width = 0.3 # 绘图 x 表示 从那里开始 plt.bar(x, Bj, bar_width) plt.bar(x+bar_width, Sh, bar_width, align="center") # 展现图片 plt.show()
两组条形图是处与同一个x处,而且y是链接起来的。
import numpy as np import matplotlib.pyplot as plt # 数据 x = np.arange(4) Bj = [52, 55, 63, 53] Sh = [44, 66, 55, 41] bar_width = 0.3 # 绘图 plt.bar(x, Bj, bar_width) plt.bar(x, Sh, bar_width, bottom=Bj) # 展现图片 plt.show()
- 对于图例:
先可选属性里添加label=“”,标签
再使用plt.lengd()显示。
- 对于数据的标签
使用任意方向的标签来标注,再由x,y数据肯定坐标。
- tick_label=str,用来显示自定义坐标轴
""" 默认的是竖值条形图 """ import numpy as np import matplotlib.pyplot as plt import matplotlib # 将全局的字体设置为黑体 matplotlib.rcParams['font.family'] = 'SimHei' # 数据 N = 5 y = [20, 10, 30, 25, 15] x = np.arange(N) # 添加地名坐标 str1 = ("北京", "上海", "武汉", "深圳", "重庆") # 绘图 x x轴, height 高度, 默认:color="blue", width=0.8 p1 = plt.bar(x, height=y, width=0.5, label="城市指标", tick_label=str1) # 添加数据标签 for a, b in zip(x, y): plt.text(a, b + 0.05, '%.0f' % b, ha='center', va='bottom', fontsize=10) # 添加图例 plt.legend() # 展现图形 plt.show()