Pandas 条形图:添加标记以区分 0 和 NaN

Pandas bar plot: Add marker to distinguish 0 and NaN

我在 Python 中有以下 pandas DataFrame:

df = pd.DataFrame([10,0,np.nan,8],index=[1947,1948,1949,1950], columns=['values'])
df
      values
1947      10
1948       0
1949     NaN
1950       8

我想使用 df.plot(kind='bar') 绘制条形图。

如何添加一种标记来区分 0NaN(并将其添加到图例中)?

一般结果如下所示:

编辑:好吧,最好是这样的:

我尝试将 'scatter' 选项与 firelynx 的第一个解决方案结合使用,但仍然出现一些错误...

可视化 nan 非常容易,如果您没有任何特定要求,这里是多种方法之一:

df['isnan'] = pd.isnull(df['values'])
df.plot(kind='bar')

这是另一种方式:

df['values'] = df['values'].fillna(-1)
df.plot(kind='bar')

和往常一样 pandas 绘图,一旦你想要某种东西完全是一种方式,它就会复杂得多。

import matplotlib.pyplot as plt
import matplotlib.ticker as plticker

markers = df[df['isnan']]
fig, ax1 = plt.subplots()
ax1.bar(df.index, df['values'], 0.4, align='center')       
ax1.plot(markers.index, markers, 'ro')
loc = plticker.MultipleLocator(base=1.0)
ax1.xaxis.set_major_locator(loc)
ax1.xaxis.set_ticklabels(["","1947", "1948", "1949", "1950"])
plt.show()

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches

df = pd.DataFrame([10,0,np.nan,8],index=[1947,1948,1949,1950], columns=['values'])
ax = df.plot(kind='bar', color='gray', alpha=0.5)
ax.get_figure().set_facecolor('white')

nan_idx = np.where(df['values'].isnull())[0]
plt.axvspan(nan_idx-0.25, nan_idx+0.25, facecolor='white', alpha=0.5, hatch='X')

nan_legend = mpatches.Patch(facecolor='white', edgecolor='gray', hatch='X', label='nan Value')
ordinary_legend = mpatches.Patch(color='gray', label='ordinary Value')
plt.legend(handles=[nan_legend, ordinary_legend])

plt.show()