首页 文章

Pandas bar plot:添加标记以区分0和NaN

提问于
浏览
1

我在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 之间的区别(并将其添加到图例中)?

通用结果如下所示:
Bar plot of the values from the dataframe, showing 1947 as 10, 1948 as 0, 1949 as 0 and 1950 as 8

编辑:嗯,最好的是:
enter image description here

我试图使用'scatter'选项结合firelynx的第一个解决方案,但仍然遇到一些错误......

2 回答

  • 1

    如果您没有任何具体要求,可以很容易地想象出nans,这是以下几种方法之一:

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

    enter image description here

    这是另一种方式:

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

    enter image description here

    和大熊猫一样,一旦你想要一种完全一种方式,它就会复杂得多 .

    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()
    

    enter image description here

  • 1

    enter image description here

    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()
    

相关问题