fill_between、bar

1,588 阅读3分钟

fill_between

Axes.fill_between(self, x, y1, y2=0, where=None, interpolate=False, step=None,*,data=None,**kwargs)

填充两个曲线之间的区域。

参数

x:有一定长度的数组,定于曲线的x轴

y1:定义第一条线。

y2:定义第二条线。默认值为0(不给出y2)

where:布尔数组,可选参数,默认值为空。最后的图像会填充的部分就是where指定的部分。要注意在两个False之间的区域不会被填充,而且邻接False的True点不会填充。

interpolate:当两条线有交叉并且where参数起作用的时候这个参数才会起作用。一般来说,两条线交叉的地方的x轴的值不一定会在前面定义的x数组里面,比如两个曲线交叉的点为(x,y),x为小数,但是所有的x数组都是整数。这个时候填充的部分不会在交叉的部位体现出来,而是简单的把这个点裁剪。

如果把这个参数设置为True,填充将会完全把这个交叉的细节表现出来,这个时候x的取值会被扩展到取到这个交叉点。


import matplotlib.pyplot as plt
import numpy as np
fig,(ax1,ax2)=plt.subplots(2,1,sharex=True)
x=np.linspace(0,10,100)
y1=np.sin(x)
ax1.fill_between(x,y1,where=y1>0)
ax2.fill_between(x,y1,where=y1>0,interpolate=True)
ax1.set_title('not_interpolate')
ax2.set_title('interpolate')


可以看到在接近x=6的位置设置了interpolate的图像完全展示了交叉点的细节;没有设置interpolate的图像没有展示交叉点的细节,只是简单地把交叉点截取(裁剪)。

step:与Axes.step()的参数where一样,有{'pre','post','mid'}可以选择。把函数图像变成阶梯参数。


import matplotlib.pyplot as plt
import numpy as np
fig=plt.figure()
ax=fig.gca()
ax=plt.fill_between(x,y1,y2,step='pre')


要注意step参数的值要设置为'pre',也就是字符串类型的参数。

data:与Axes.plot()的data参数一样,但是如果设置了data参数,‘where’,‘x’,‘y1

’,‘y2’参数就会被替代。

**arg:Axes.plot()的曲线参数相同。

bar

Axes.bar(self, x, height, width=0.8, bottom=None,*, align=’center’, data=None,**kwargs)

可以带误差条的条形图

参数

self:python函数定义自带参数。

x:条形图的x轴,参数必须是标量序列。

height:标量或者标量序列,条形图的条形高度。

width:标量或者标量序列,可选参数。条形图的宽度,默认值是0.8

bottom:标量或者数组类型的参数,可选参数。条形图的底部起始位置。


import matplotlib.pyplot as plt
import numpy as np
x=('x1','x2','x3')
fig,(ax1,ax2)=plt.subplots(2,1)
y1=(1,2,3)
bottom=(3,2,1)
ax1.bar(x,y1)
ax2.bar(x,y1,bottom=bottom)
ax1.set_title('bottom=default(0.0)')
ax2.set_title('set_bottom')


align:可选参数,选择的参数为:{'center','edge'}。默认值为center,条形图对齐x轴的方式。

center:中间位置。

edge:边缘位置,如果是正数,表示对其左边缘,如果表示宽度的参数width是负数,则对其右边缘。


import matplotlib.pyplot as plt
import numpy as np
x=('x1','x2','x3')
y1=(1,2,3)
title=['center','right edge','left edge']
fig,ax=plt.subplots(2,2)
flag=0
for i in range(2):
    for j in range(2):
         if i==1&j==1:
             break
         ax[i,j].set_title(title[flag])
         flag=flag+1
         
ax[0,0].bar(x,y1)
Out[55]: <BarContainer object of 3 artists>
ax[0,1].bar(x,y1,align='edge')
Out[56]: <BarContainer object of 3 artists>
ax[1,0].bar(x,y1,align='edge',width=-0.8)


其他参数

color:标量或者数组形状,条形图的颜色。

edgecolor:同上,条形图边缘颜色。

label:条形图的图例

xeeryeer:表示条形图的误差。

标量:给所有的条形上下对称分配误差线,值都为该标量。

shape(N,):一维数组,对称且对应给每一个条形分配误差线。

shape(2,N):第一个维度给较低的误差线赋值,第二个维度给较高的误差线赋值。