matplotlib:忽略缺失数据在点之间画线
- 2025-03-14 08:57:00
- admin 原创
- 50
问题描述:
我有一组数据,我想将其绘制成线图。对于每个系列,有些数据缺失(但每个系列都不同)。目前,matplotlib 不会绘制跳过缺失数据的线:例如
import matplotlib.pyplot as plt
xs = range(8)
series1 = [1, 3, 3, None, None, 5, 8, 9]
series2 = [2, None, 5, None, 4, None, 3, 2]
plt.plot(xs, series1, linestyle='-', marker='o')
plt.plot(xs, series2, linestyle='-', marker='o')
plt.show()
导致绘图中的线条有间隙。我如何告诉 matplotlib 在间隙处画线?(我宁愿不必插入数据)。
解决方案 1:
您可以通过以下方式屏蔽 NaN 值:
import numpy as np
import matplotlib.pyplot as plt
xs = np.arange(8)
series1 = np.array([1, 3, 3, None, None, 5, 8, 9]).astype(np.double)
s1mask = np.isfinite(series1)
series2 = np.array([2, None, 5, None, 4, None, 3, 2]).astype(np.double)
s2mask = np.isfinite(series2)
plt.plot(xs[s1mask], series1[s1mask], linestyle='-', marker='o')
plt.plot(xs[s2mask], series2[s2mask], linestyle='-', marker='o')
plt.show()
这导致
解决方案 2:
引用@Rutger Kassies(链接):
Matplotlib 仅在连续(有效)数据点之间画一条线,并在 NaN 值处留下间隙。
如果你使用Pandas,则有一个解决方案:
#pd.Series
s.dropna().plot() #masking (as @Thorsten Kranz suggestion)
#pd.DataFrame
df['a_col_ffill'] = df['a_col'].ffill()
df['b_col_ffill'] = df['b_col'].ffill() # changed from a to b
df[['a_col_ffill','b_col_ffill']].plot()
解决方案 3:
使用 pandas 的解决方案:
import matplotlib.pyplot as plt
import pandas as pd
def splitSerToArr(ser):
return [ser.index, ser.as_matrix()]
xs = range(8)
series1 = [1, 3, 3, None, None, 5, 8, 9]
series2 = [2, None, 5, None, 4, None, 3, 2]
s1 = pd.Series(series1, index=xs)
s2 = pd.Series(series2, index=xs)
plt.plot( *splitSerToArr(s1.dropna()), linestyle='-', marker='o')
plt.plot( *splitSerToArr(s2.dropna()), linestyle='-', marker='o')
plt.show()
在 Pandas 中绘图时,此splitSerToArr
函数非常方便。这是输出:
解决方案 4:
如果不使用插值,您需要从数据中删除 None。这也意味着您需要删除系列中与 None 相对应的 X 值。这里有一个(丑陋的)一行代码可以做到这一点:
x1Clean,series1Clean = zip(* filter( lambda x: x[1] is not None , zip(xs,series1) ))
lambda 函数对 None 值返回 False,从列表中过滤 x,series 对,然后将数据重新压缩回其原始形式。
解决方案 5:
不管怎样,经过反复尝试,我想对 Thorsten 的解决方案做一点澄清。希望这能为尝试过此方法后寻找其他解决方案的用户节省时间。
在使用时我无法成功解决相同的问题
from pyplot import *
并试图密谋
plot(abscissa[mask],ordinate[mask])
似乎需要使用它import matplotlib.pyplot as plt
来获得正确的 NaN 处理,尽管我不知道为什么。
解决方案 6:
pandas DataFrames 的另一种解决方案:
plot = df.plot(style='o-') # draw the lines so they appears in the legend
colors = [line.get_color() for line in plot.lines] # get the colors of the markers
df = df.interpolate(limit_area='inside') # interpolate
lines = plot.plot(df.index, df.values) # add more lines (with a new set of colors)
for color, line in zip(colors, lines):
line.set_color(color) # overwrite the new lines colors with the same colors as the old lines
解决方案 7:
我遇到了同样的问题,但掩码消除了中间的点,并且线无论如何都被切断了(我们在图片中看到的粉红色线条是唯一连续的非 NaN 数据,这就是线条的原因)。以下是屏蔽数据的结果(仍然有间隙):
xs = df['time'].to_numpy()
series1 = np.array(df['zz'].to_numpy()).astype(np.double)
s1mask = np.isfinite(series1)
fplt.plot(xs[s1mask], series1[s1mask], ax=ax_candle, color='#FF00FF', width = 1, legend='ZZ')
可能是因为我使用 finplot(绘制蜡烛图),所以我决定用线性公式 y2-y1=m(x2-x1) 来制作缺失的 Y 轴点,然后制定在缺失点之间生成 Y 值的函数。
def fillYLine(y):
#Line Formula
fi=0
first = None
next = None
for i in range(0,len(y),1):
ne = not(isnan(y[i]))
next = y[i] if ne else next
if not(next is None):
if not(first is None):
m = (first-next)/(i-fi) #m = y1 - y2 / x1 - x2
cant_points = np.abs(i-fi)-1
if (cant_points)>0:
points = createLine(next,first,i,fi,cant_points)#Create the line with the values of the difference to generate the points x that we need
x = 1
for p in points:
y[fi+x] = p
x = x + 1
first = next
fi = i
next = None
return y
def createLine(y2,y1,x2,x1,cant_points):
m = (y2-y1)/(x2-x1) #Pendiente
points = []
x = x1 + 1#first point to assign
for i in range(0,cant_points,1):
y = ((m*(x2-x))-y2)*-1
points.append(y)
x = x + 1#The values of the line are numeric we don´t use the time to assign them, but we will do it at the same order
return points
然后我使用简单的调用函数来填补之间的空白y = fillYLine(y)
,我的 finplot 就像:
x = df['time'].to_numpy()
y = df['zz'].to_numpy()
y = fillYLine(y)
fplt.plot(x, y, ax=ax_candle, color='#FF00FF', width = 1, legend='ZZ')
您需要认为 Y 变量中的数据仅用于绘图,我需要操作之间的 NaN 值(或将它们从列表中删除),这就是我从 pandas 数据集创建 Y 变量的原因df['zz']
。
注意:我注意到在我的例子中数据被消除了,因为如果我不屏蔽 X (xs),值会在图表中向左滑动,在这种情况下它们会变成连续的非 NaN 值,并且会绘制连续的线,但会向左缩小:
fplt.plot(xs, series1[s1mask], ax=ax_candle, color='#FF00FF', width = 1, legend='ZZ') #No xs masking (xs[masking])
这让我想到,有些人之所以要使用掩模版,是因为他们只是绘制那条线,或者非掩模版数据和掩模版数据之间没有太大区别(间隙很少,不像我的数据有很多间隙)。
解决方案 8:
也许我没抓住重点,但我相信 Pandas 现在会自动执行此操作。下面的示例有点复杂,需要互联网访问,但早年中国的线路有很多空白,因此使用直线段。
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# read data from Maddison project
url = 'http://www.ggdc.net/maddison/maddison-project/data/mpd_2013-01.xlsx'
mpd = pd.read_excel(url, skiprows=2, index_col=0, na_values=[' '])
mpd.columns = map(str.rstrip, mpd.columns)
# select countries
countries = ['England/GB/UK', 'USA', 'Japan', 'China', 'India', 'Argentina']
mpd = mpd[countries].dropna()
mpd = mpd.rename(columns={'England/GB/UK': 'UK'})
mpd = np.log(mpd)/np.log(2) # convert to log2
# plots
ax = mpd.plot(lw=2)
ax.set_title('GDP per person', fontsize=14, loc='left')
ax.set_ylabel('GDP Per Capita (1990 USD, log2 scale)')
ax.legend(loc='upper left', fontsize=10, handlelength=2, labelspacing=0.15)
fig = ax.get_figure()
fig.show()
扫码咨询,免费领取项目管理大礼包!