Search code examples
pandasdataframelabelbar-chart

Pandas: plot a filtered dataframe showing all labels


I've looked for an answer everywhere but I can't get my head around this...

I need to plot a bar graph of a filtered dataframe with pandas:

import pandas as pd
import matplotlib.pyplot as plt

nestedDict = {'A': {'apples': 3,
                    'bananas': 5,
                    'oranges': 6,
                    'kiwis': 9},
              'B': {'dog': 1,
                  'bananas': 9,
                  'oranges': 3,
                  'kiwis': 1},
              'C': {'rain': 6,
                  'bananas': 9,
                  'oranges': 3,
                  'kiwis': 3}}


def plot_lig():
  df = pd.DataFrame.from_dict(nestedDict)

  df.index = df.index.str.split()
  df.index.name = 'residue'
  df2 = df[df <= 6].dropna()
  df2.plot(kind='bar')
  plt.show()
  plt.close()

plot_lig()

When I run this function the bar plot shows only "oranges".

If I remove .dropna, instead, it will include ALL the labes in the X axis (all the ticks) even if the filtered result will not be plotted due to the filter.

I want to plot all the result from my filtered selection discarding the filtered data and their correspective x ticks.

Thanks again!


Solution

  • solved:

    nestedDict = nestedDict[nestedDict <= -0.25] #set filter first
    nestedDict.dropna(how='all', inplace=True) #added the 'all' keyword makes you keep the columns with single outliers
    df2.plot(kind='bar', edgecolor='black')
    plt.legend(['X var', 'Y var', 'Z var'])
    plt.show()
    plt.close()
    

    hope this might help someone else!