使用NaN图有麻烦

问题描述 投票:0回答:1

我正在尝试绘制一个百分比堆积的条形图,其中有5条。 2条没有数据,但不能从图表中排除。我将此值设置为NaN(因为稍后需要计算均值)。在这种情况下,这2个是列表中的第一个条目。这导致未显示图表的顶部。我不明白的是,当我切换第一个和第二个,使第二个输入为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 first

NaN秒:NaN second

numpy matplotlib bar-chart nan stacked-chart
1个回答
0
投票

您可以将数据转换为numpy数组,然后搜索NaN并将其替换为0。

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

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

将得到:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.