当数据具有NaN时在matplotlib中的线图中绘制阴影的不确定区域 [英] Plotting shaded uncertainty region in line plot in matplotlib when data has NaNs

查看:342
本文介绍了当数据具有NaN时在matplotlib中的线图中绘制阴影的不确定区域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个看起来像这样的情节:

I would like a plot which looks like this:

我正在尝试使用matplotlib做到这一点:

I am trying to do this with matplotlib:

fig, ax = plt.subplots()

with sns.axes_style("darkgrid"):
    for i in range(5):
        ax.plot(means.ix[i][list(range(3,104))], label=means.ix[i]["label"])
        ax.fill_between(means.ix[i][list(range(3,104))]-stds.ix[i][list(range(3,104))], means.ix[i][list(range(3,104))]+stds.ix[i][list(range(3,104))])
    ax.legend()

我希望阴影区域的颜色与中间的线相同.但是现在,我的问题是means有一些NaN,而fill_between不接受.我得到了错误

I want the shaded region to be the same colour as the line in the centre. But right now, my problem is that means has some NaNs and fill_between does not accept that. I get the error

TypeError:输入类型不支持ufunc'isfinite',并且 根据以下说明,无法将输入安全地强制转换为任何受支持的类型 强制转换为安全"

TypeError: ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

关于如何实现自己想要的目标的任何想法?该解决方案不需要使用matplotlib,只要它可以绘制出我的一系列点及其对多个序列的不确定性即可.

Any ideas on how I could achieve what I want? The solution doesn't need to use matplotlib as long as it can plot my series of points with their uncertainties for multiple series.

推荐答案

好.因此,问题之一是我的数据的dtypeobject而不是float,这在查看数字是否有限时导致fill_between失败.我最终设法做到了(a)转换为float,然后(b)解决颜色不确定和线条匹配的问题,使用调色板.所以我有:

Ok. So one of the problem was that the dtype of my data was object and not float and this caused fill_between to fail when it looked to see if the numbers were finite. I finally managed to do it by (a) converting to float and then (b) to solve the problem of the matching colours for uncertainty and line, to use a colour palette. So I have:

import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
fig, ax = plt.subplots()
clrs = sns.color_palette("husl", 5)
with sns.axes_style("darkgrid"):
    epochs = list(range(101))
    for i in range(5):
        meanst = np.array(means.ix[i].values[3:-1], dtype=np.float64)
        sdt = np.array(stds.ix[i].values[3:-1], dtype=np.float64)
        ax.plot(epochs, meanst, label=means.ix[i]["label"], c=clrs[i])
        ax.fill_between(epochs, meanst-sdt, meanst+sdt ,alpha=0.3, facecolor=clrs[i])
    ax.legend()
    ax.set_yscale('log')

给了我以下结果:

这篇关于当数据具有NaN时在matplotlib中的线图中绘制阴影的不确定区域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆