Search code examples
pandasplot

fails to label x by its values in a pandas bar plot


The following code fails to shows the Ref values 'F', 'C', 'H', 'B', 'G', 'A', 'D', 'E'. Only index values are shown:

import pandas as pd
import matplotlib.pyplot as plt

data = pd.DataFrame({'Ref': ['F', 'C', 'H', 'B', 'G', 'A', 'D', 'E'],
                     'Nombre Pieces': [150, 130, 100, 60, 30, 30, 20, 10],
                     'PC100': [28.301887, 52.830189, 71.698113, 83.018868, 88.679245, 94.339623, 98.113208, 100.000000],
                     'categories': ['a', 'a', 'a', 'b', 'b', 'b', 'b', 'b']})

colors = {'a': 'red', 'b': 'blue'}

data['PC100'].plot(kind='bar', color=data['categories'].map(colors))

plt.show()

How to edit this code? Thanks


Solution

  • To only plot:

    data.set_index('Ref')['PC100'].plot(kind='bar', color=data['categories'].map(colors))
    

    For permanent index change on your dataframe and plot:

    data.set_index('Ref', inplace=True)
    data['PC100'].plot(kind='bar', color=data['categories'].map(colors))
    plt.show()
    

    The result is same when you plot with the following plot: enter image description here