簡體   English   中英

更改線圖中線段的顏色

[英]Change color of lineplot mid-line segment

我需要 plot 一行 plot。 我想 plot 線圖的所有部分低於零藍色,所有部分高於紅色。

這是我到目前為止所管理的:

import numpy as np
import xarray as xr
import matplotlib.pyplot as plt

x = np.linspace(0, 1, 40)
y = np.random.random(len(x))-0.5
da = xr.DataArray(y, dims=('x',), coords={'x':x})

fig = plt.figure(figsize=(12,6))
ax = fig.add_subplot(1, 1, 1)
da.plot(ax=ax, color='red', linewidth=3)
da.where(y<0).plot(ax=ax, color='blue', linewidth=3)
plt.show()

這是我從這個腳本中得到的:

我得到的圖片。只有完全低於零的線段是藍色的

但我想要的是顏色在閾值 0 處改變,就像這個例子(我已經修改以顯示我想要的):

我想要的圖片。零以下的所有線都是藍色的

我在這里查看了一些建議,例如這里: Plot:顏色都大於不同的顏色

但我得到與該解決方案相同的數字。 似乎解決方案在於它們的所有線段都非常短,因此您不會注意到通過閾值的線段不會在閾值處改變顏色,並且只有下一個線段以不同的方式繪制顏色。

有沒有一種簡單的方法可以做到這一點? 還是我必須手動分離跨越閾值的線段?

謝謝

似乎解決方案在於它們的所有線段都非常短,因此您不會注意到通過閾值的線段不會在閾值處改變顏色,並且只有下一個線段以不同的方式繪制顏色。

您可以只插入您的數據,以便這也適用於您的數據。

在此處輸入圖像描述

import numpy as np
import xarray as xr
import matplotlib.pyplot as plt

xx = np.linspace(0, 1, 40)
yy = np.random.random(len(xx))-0.5

x = np.linspace(0, 1, 4000)
y = np.interp(x, xx, yy) # linear piecewise interpolation

da = xr.DataArray(y, dims=('x',), coords={'x':x})
fig = plt.figure(figsize=(12,6))
ax = fig.add_subplot(1, 1, 1)
da.plot(ax=ax, color='red', linewidth=3)
da.where(y<0).plot(ax=ax, color='blue', linewidth=3)
plt.show()

暫無
暫無

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

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