目录
- 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带有误差棒条形图内容请搜索悠久资源网以前的文章或继续浏览下面的相关文章希望大家以后多多支持悠久资源网!
您可能感兴趣的文章:
- python 画条形图(柱状图)实例
- python绘制条形图方法代码详解
- python绘制横向水平柱状条形图
- Python数据可视化之绘制柱状图和条形图
- python+matplotlib绘制3D条形图实例代码
- python数据可视化之条形图画法
- python使用Matplotlib画条形图
- Python pyecharts绘制条形图详解