英文:
Shading specific area under a line using matplotlib
问题
I am trying to shade the area under my line plot so that only the area that has a y value that is greater than 0.5 (shown by the black horizontal line) is shaded.
这是我目前的代码:
n = 256
X = np.linspace(-np.pi, np.pi, n, endpoint=True)
Y = np.sin(2 * X)
fig, ax = plt.subplots()
ax.plot(X, Y, color='blue', alpha=1.0)
ax.fill_between(X, 0, Y, where=(Y > 0.5), color='blue', alpha=0.2)
plt.axhline(0.5, color="black")
plt.show()
这是我想要的图形效果:
英文:
I am trying to shade the area under my line plot so that only the area that has a y value that is greater than 0.5 (shown by the black horizontal line) is shaded.
This is my current code:
n = 256
X = np.linspace(-np.pi, np.pi, n, endpoint=True)
Y = np.sin(2 * X)
fig, ax = plt.subplots()
ax.plot(X, Y, color='blue', alpha=1.0)
ax.fill_between(X, 0, Y, color='blue', alpha=.2)
plt.axhline(0.5, color="black")
plt.show()
This is what I want the plot to look like:
答案1
得分: 0
你可以使用ax.fill_between
中的where
参数(文档在此)来实现你想要的效果。查看下面的代码:
import matplotlib.pyplot as plt
import numpy as np
n = 256
X = np.linspace(-np.pi, np.pi, n, endpoint=True)
Y = np.sin(2 * X)
fig, ax = plt.subplots()
ax.plot(X, Y, color='blue', alpha=1.0)
ax.fill_between(X,Y, 0.5,where=Y>0.5,color='blue', alpha=.2)
plt.axhline(0.5, color="black")
plt.show()
英文:
You could use the where
argument in ax.fill_between
(doc here) to achieve what you want. See code below:
import matplotlib.pyplot as plt
import numpy as np
n = 256
X = np.linspace(-np.pi, np.pi, n, endpoint=True)
Y = np.sin(2 * X)
fig, ax = plt.subplots()
ax.plot(X, Y, color='blue', alpha=1.0)
ax.fill_between(X,Y, 0.5,where=Y>0.5,color='blue', alpha=.2)
plt.axhline(0.5, color="black")
plt.show()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论