簡體   English   中英

Matplotlib 多個fill_between 反轉?

[英]Matplotlib multiple fill_between invert?

為了跟進上一個問題( Matplotlib fill_between invert? ),我想為多個區域反轉 fill_between。 為原始問題提出的解決方案,反轉前景和背景,不適用於多個區域。 一些代碼如下。 有什么想法嗎?

import numpy as np
import matplotlib.pyplot as plt

# Doesn't work: want to invert filled and empty regions
def f1(x): return 32.0 * x + 2.0
def f2(x): return -55.0 * x
def f3(x): return 15.0 * x + 2.0
def f4(x): return -28.0 * x
xRng=[-1, 1]
plt.plot(xRng, [f1(x) for x in xRng], 'b-', alpha=0.5)
plt.plot(xRng, [f2(x) for x in xRng], 'r-', alpha=0.5)
plt.plot(xRng, [f3(x) for x in xRng], 'b-', alpha=0.5)
plt.plot(xRng, [f4(x) for x in xRng], 'r-', alpha=0.5)
plt.fill_between(xRng, [f1(x) for x in xRng], [f2(x) for x in xRng], color='g', alpha=0.1) # Would like the fill inverted
plt.fill_between(xRng, [f3(x) for x in xRng], [f4(x) for x in xRng], color='g', alpha=0.3) # Would like the fill inverted
plt.title('Want to invert filled and empty regions'); plt.show()

如何反轉

您可以使用axvspan設置背景,然后反轉要填充區域的 alpha。 這是一個例子:

x = np.linspace(-1, 1, 100)
y1 = 32.0 * x + 2.0
y2 = -55.0 * x
y3 = 15.0 * x + 2.0
y4 = -28.0 * x

fig, ax = plt.subplots()

ax.plot(x, y1, 'b', alpha=0.5)
ax.plot(x, y2, 'r', alpha=0.5)
ax.plot(x, y3, 'b', alpha=0.5)
ax.plot(x, y4, 'r', alpha=0.5)

ax.axvspan(x.min(), x.max(), color='g', alpha=0.5)

ax.fill_between(x, y1, y2, color='w', alpha=0.5)
ax.fill_between(x, y3, y4, color='w', alpha=1.0)

在此處輸入圖像描述

您還可以將整個軸 object 設為綠色,盡管您最終可能想要稍微調整顏色以使其看起來像您想要的那樣:

fig, ax = plt.subplots(subplot_kw={'facecolor': 'g', 'alpha': 0.5})

此外,在這種情況下,刪除帶有axvspan的行。

在此處輸入圖像描述

如果您設置,這兩個選項看起來相似

ax.set_xlim(x.min(), x.max())

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM