Skip to main content
 首页 » 编程设计

python之Pandas 条形图 : Add marker to distinguish 0 and NaN

2024年08月25日32zhwl

我在 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') 绘制条形图。

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

一般结果如下所示:

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

我尝试将“分散”选项与 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()