首页 > 解决方案 > 使用 NaN 图形时遇到问题

问题描述

我正在尝试制作一个带有 5 个条形的百分比堆积条形图。2 个柱没有数据,但不能从图表中排除。我设置了这个值 NaN (因为我需要稍后计算平均值)。在这种情况下,这两个中的一个是列表中的第一个条目。这导致不显示图表的顶部。我不明白的是,当我切换第一个和第二个,使第二个条目为NaN时,没有问题。

代码:这里首先是 NaN,其次是 3,这不起作用。切换 NaN 和 3 确实有效(见下图)

import numpy as np
import matplotlib.pyplot as plt
from math import nan

#Data
goed1 = [nan,3,152,9, nan]

tot1 = [1,1,15,2,1]
total = [(i * 16 ) for i in tot1]

fout1 = np.zeros(5)

for i in range(len(goed1)):
    fout1[i] = total[i] - goed1[i]

data = {'Goed': goed1, 'Fout': fout1}


#Grafiek
fig, ax = plt.subplots()

r = [0,1,2,3,4]
df = pd.DataFrame(data)

#naar percentage
totaal = [i + j for i,j in zip(df['Goed'], df['Fout'])]
goed = [i / j * 100 for i,j in zip(df['Goed'], totaal)]
fout = [i / j * 100 for i,j in zip(df['Fout'], totaal)]

#plot
width = 0.85
names = ('Asphalt cover','Special constructions','Gras revetments','Non-flood defensive elements','Stone revetments')

plt.bar(r, goed, color='#b5ffb9', edgecolor='white', width=width, label="Detected")
plt.bar(r, fout, bottom=goed, color='#f9bc86', edgecolor='white', width=width, label="Missed")

# Add a legend
plt.legend(loc='upper left', bbox_to_anchor=(1,1), ncol=1)
plt.title('Boezemkade')

# Custom x axis
plt.xticks(r, names, rotation = 20, horizontalalignment = 'right')

# Show graphic
plt.show()

如果有人知道如何解决此问题,我们将不胜感激。

情节:

首先是 NaN: 首先是 NaN

南二: 南秒

标签: numpymatplotlibbar-chartnanstacked-chart

解决方案


您可以将数据转换为 numpy 数组,然后搜索 NaN 的位置并将它们替换为 0。

goed1 = np.array([nan,3,152,9, nan])

where_are_NaNs = np.isnan(goed1)
goed1[where_are_NaNs] = 0

它将导致:

在此处输入图像描述


推荐阅读