2017-01-30 71 views
0

我想填充曲線y1 = x^3然後行y2 = 3x-2之間的區域。 下面是代碼,我會做到這一點,但是,我希望把與發生時Y1 < Y2(我曾與fill_between的地方選項來完成的)的限制,並且X < 1.用兩個限制在Matplotlib之間填充兩行

問題下面的代碼是曲線之間的區域填充x> 1。我想繪製這些圖表的範圍[-2.5,2.5]。如何讓matplotlib在x> 1的曲線之間停止填充?

我的代碼:

import matplotlib.pyplot as plot 
import numpy as np 

x = np.linspace(-2.5, 2.5, 100) 
y1 = np.array([i**3 for i in x]) 
y2 = np.array([3*i-2 for i in x]) 

fig = plot.figure() 
ax = fig.add_subplot(1,1,1) 
ax.plot(x, y1, label=r"$y=x^3$") 
ax.plot(x, y2, label=r"$y=3x-2$") 
ax.spines['left'].set_position('center') 
ax.spines['right'].set_color('none') 
ax.spines['bottom'].set_position('center') 
ax.spines['top'].set_color('none') 
ax.spines['left'].set_smart_bounds(True) 
ax.spines['bottom'].set_smart_bounds(True) 
ax.xaxis.set_ticks_position('bottom') 
ax.yaxis.set_ticks_position('left') 
ax.fill_between(x, y1, y2, where=y2<y1, facecolor='green') 
ax.legend() 

plot.show() 

回答

0

我知道了。最簡單的方法是定義3個新變量u,v和w,其中u保存v和w的x值,v = x^3,w = 3x-2。

u=x[x<1] 
v=y1[y1<1] 
w=y2[y2<1] 

然後用fill_between繪製這些值:

ax.fill_between(u, v, w, where=w<v, facecolor='green') 
相關問題