Search code examples
pandasmatplotlibseabornvisualizationcrosstab

plot a bar chart in python using specific values


I did a pandas crosstab to check the percentage of each of the 0 and 1 values across the index, but i want to visualize the results of only the values for 1, this is my code,

pandas.crosstab(df['item'], df['values'],normalize='index').mul(100).sort_values(by=1,ascending=False)

so the values are only 0 and 1, so I sorted it using 1, but I want to visualize only the 1 values, not the 0 and 1, how do I do this


Solution

  • You can select the 1 column and create a bar plot:

    import matplotlib.pyplot as plt
    import pandas as pd
    import numpy as np
    
    df = pd.DataFrame({'item': np.random.choice([*'abcdef'], 1000),
                       'values': np.random.randint(0, 2, 1000)})
    crosstab_df = pd.crosstab(df['item'], df['values'], normalize='index').mul(100).sort_values(by=1, ascending=False)
    ax = crosstab_df[1].plot.bar()
    ax.bar_label(ax.containers[0], fmt='%.2f %%')
    ax.margins(y=0.1)
    plt.show()
    

    bar plot