用matplotlib填充线下特定区域

huangapple go评论58阅读模式
英文:

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()

这是我想要的图形效果:

用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.

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()

用matplotlib填充线下特定区域

This is what I want the plot to look like:

用matplotlib填充线下特定区域

答案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()

用matplotlib填充线下特定区域

英文:

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()

用matplotlib填充线下特定区域

huangapple
  • 本文由 发表于 2023年4月19日 23:57:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/76056576.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定