目录
- bar和barh
 - 加入误差棒
 - 定制误差棒颜色
 
bar和barh
在matplotlib中,通过bar和barh来绘制条形图,分别表示纵向和横向的条形图。二者的输入数据均主要为高度x和标签height,示例如下
import matplotlib.pyplot as plt import numpy as np x = np.arange(8) fig = plt.figure() ax = fig.add_subplot(1,2,1) ax.bar(x.astype(str), x) ax = fig.add_subplot(1,2,2) ax.barh(x.astype(str), x) plt.show()
效果为

其中,左侧为纵向的条形图,右侧为横向的条形图,二者分别由bar和barh实现。
加入误差棒
在bar或者barh中,误差线由xerr, yerr来表示,其输入值为 1 × N 1\times N 1×N或者 2 × N 2\times N 2×N维数组。
errs = np.random.rand(2, 8) fig = plt.figure() ax = fig.add_subplot(1,2,1) ax.bar(x.astype(str), x, yerr=errs, capsize=5) ax = fig.add_subplot(1,2,2) ax.barh(x.astype(str), x, xerr=errs, capsize=5) plt.show()
从代码可知,纵向的条形图和横向的条形图有着不同的误差棒参数,其中纵向的条形图用yerr作为误差棒;横向条形图用xerr做误差棒,效果如图所示

如果反过来,那么效果会非常滑稽
errs = np.random.rand(2, 8) fig = plt.figure() ax = fig.add_subplot(1,2,1) ax.bar(x.astype(str), x, xerr=errs, capsize=5) ax = fig.add_subplot(1,2,2) ax.barh(x.astype(str), x, yerr=errs, capsize=5) plt.show()

在熟悉基础功能之后,就可以对条形图和误差棒进行更高级的定制。bar和barh函数的定义为
Axes.bar(x, height, width=0.8, bottom=None, *, align='center', data=None, **kwargs) Axes.barh(y, width, height=0.8, left=None, *, align='center', data=None, **kwargs)
其中,x, y, height, width等参数自不必多说,而颜色、边框颜色等的定制参数,在**kwarg中,可通过下列参数来搞定
- color 控制条形图颜色
 - edgecolor 控制条形图边框颜色
 - linewidth 控制条形图边框粗细
 - ecolor 控制误差线颜色
 - capsize 误差棒端线长度
 
上面的参数中,凡是涉及颜色的,均支持单个颜色和颜色列表,据此可对每个数据条进行定制。
定制误差棒颜色
下面就对条形图和误差棒的颜色进行定制
xs = np.arange(1,6)
errs = np.random.rand(5)
colors = ['red', 'blue', 'green', 'orange', 'pink']
plt.bar(xs.astype(str), xs, yerr=errs, color='white',
    edgecolor=colors, ecolor=colors)
plt.show()
其中,color表示条形图的数据条内部的颜色,此处设为白色。然后将数据条的边框和误差棒,均设为colors,即红色、蓝色、绿色、橘黄色以及粉色,最终得到效果如下

到此这篇关于python绘制带有误差棒条形图的实现的文章就介绍到这了,更多相关python带有误差棒条形图内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
	声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。
		
评论(0)