假設我有多個數學函式f1, f2,f3由 Python 函式表示。我想在 [0, 1] 的域上將它們一起繪制。這是它的樣子
import numpy as np
import matplotlib.pyplot as plt
import math
def f1(x):
return 4*x**3 9*x**2 x 4
def f2(x):
return math.sqrt(x) / (1.01 - x)
def f3(x):
return 30 * math.cos(6 * x)
x = np.arange(0.0, 1.01, 0.01)
for f in [f1, f2, f3]:
vecf = np.vectorize(f)
y = vecf(x)
plt.plot(x, y)
plt.xlim([0, 1])
plt.xlabel(r'$x$')
plt.ylabel(r'$f(x)$')
plt.show()

但是,我想使用 突出顯示所有最低曲線段(即包絡)alpha = 1,同時alpha = 0.5用于曲線的其他部分。我想保留每條曲線的顏色。預期的情節如下所示:

誰能建議如何在 matplotlib 中實作這一目標?
uj5u.com熱心網友回復:
我嘗試做我在評論中建議的操作(“只繪制所有曲線,然后計算一個系列,它實際上是其他曲線組合中的最小值,并繪制它,但使用 100% 透明的線條顏色和陰影它上面的整個區域都是部分不透明的白色。”)我認為它非常接近您的需要:
import numpy as np
import matplotlib.pyplot as plt
import math
def f1(x):
return 4*x**3 9*x**2 x 4
def f2(x):
return math.sqrt(x) / (1.01 - x)
def f3(x):
return 30 * math.cos(6 * x)
x = np.arange(0.0, 1.01, 0.01)
# initialise min_y to all infinite, there is probably a more efficient way to do this
min_y = np.inf * np.ones(x.shape)
for f in [f1, f2, f3]:
vecf = np.vectorize(f)
y = vecf(x)
# zorder=0 to push curves below plane
plt.plot(x, y, zorder=0)
# compute min_y as we go
min_y = np.minimum(y, min_y)
# what you need, although the 1 is a bit arbitrary
# you may want to add some amount relative to the plt.ylim()
plt.fill_between(x, min_y 1, plt.ylim()[1], color='white', alpha=.5)
plt.xlim([0, 1])
plt.xlabel(r'$x$')
plt.ylabel(r'$f(x)$')
plt.show()
結果:

也許你想要一個更像 0.7 左右的 alpha,從你的例子來看。
偷偷摸摸的后續問題,也使線條變胖:
import numpy as np
import matplotlib.pyplot as plt
import math
def f1(x):
return 4*x**3 9*x**2 x 4
def f2(x):
return math.sqrt(x) / (1.01 - x)
def f3(x):
return 30 * math.cos(6 * x)
x = np.arange(0.0, 1.01, 0.01)
# initialise min_y to all infinite, there is probably a more efficient way to do this
min_y = np.inf * np.ones(x.shape)
plotted = []
for f in [f1, f2, f3]:
vecf = np.vectorize(f)
y = vecf(x)
# zorder=0 to push curves below plane
p = plt.plot(x, y, zorder=0)
# compute min_y as we go
min_y = np.minimum(y, min_y)
# keep the plotted data, to reuse when plotting fat lines
plotted.append((y, p[0].get_color()))
for y, c in plotted:
plt.plot(x, np.ma.masked_where(y > min_y, y), color=c, zorder=1, linewidth=3)
# what you need, although the 1 is a bit arbitrary - you may want to add some amount relative to the plt.ylim()
plt.fill_between(x, min_y 1, plt.ylim()[1], color='white', alpha=.7)
plt.xlim([0, 1])
plt.xlabel(r'$x$')
plt.ylabel(r'$f(x)$')
plt.show()
結果:

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/357853.html
標籤:Python 蟒蛇-3.x 功能 matplotlib 阴谋
