matplotlib色彩填充之fill、fill_between

2020-03-26  本文已影响0人  esroom

fill可以填充两条线之间的色彩

#填充x,y组成的封闭图形
from matplotlib import pyplot as plt
import numpy as np

x = [0, 0, 5, 10, 15, 15, 10, 5 ]
y = [5, 10, 15, 15, 10, 5, 0, 0]

plt.fill(x, y, color="red")

plt.xlim(-1, 16)
plt.ylim(-1, 16)

list = np.arange(0, 16, 5)

plt.xticks(list)
plt.yticks(list)

plt.show()

结果如图


fill_between填充x轴与两条y轴

from matplotlib import pyplot as plt
import numpy as np

x = np.linspace(0, 2, 500)
y1 = np.sin(2*np.pi*x)
y2 = 1.1*np.cos(3*np.pi*x)

fig, ax = plt.subplots(3, 1, sharex="all")
#填充y2与y=0之间
ax[0].fill_between(x, 0, y2, alpha=0.5)
ax[0].set_ylim(-1.2, 1.2)
#填充y2与y=1.1
ax[1].fill_between(x, y2, 1.1, alpha=0.5)
ax[1].set_ylim(-1.2, 1.2)
#填充y1, y2之间
ax[2].fill_between(x, y1, y2, alpha=0.5)
ax[2].set_ylim(-1.2, 1.2)
ax[2].set_xlim(0, 2)

plt.show()

fill_between可以x轴可以通过截取片段进行限制,如x[0:1]等;
fill_between可以通过where参数进行判断,

ax.fill_between(x, y1, y2, where=y2>=y1, facecolor="darkred", aphpa=0.7)

距离如下

from matplotlib import pyplot as plt
import numpy as np

x = np.linspace(0, 2, 500)
y1 = np.sin(2*np.pi*x)
y2 = 1.1*np.cos(3*np.pi*x)

fig, ax = plt.subplots(2, 1, sharex="all")

ax[0].plot(x, y1)
ax[0].plot(x, y2)

ax[1].fill_between(x, y1, y2, where=y1>=y2)
ax[1].fill_between(x, y1, y2, where=y1<=y2)


plt.show()

对于竖直方向的填充可以通过fill_betweenx()实现,用法类似,第一项为y轴的范围

上一篇 下一篇

猜你喜欢

热点阅读