Home > Software design >  How to add x-axis lable in python bar chart
How to add x-axis lable in python bar chart

Time:05-01

hi i am trying to print python bar chart. here is my code.. and I also attached an image of my bar chart. the problems I am facing is that I want to write name of each category of bar chart on x-axis as CAT1, CAT2, CAT3, CAT4. right now its printing 0, 1, 2 on x-axis

and I also want to change the purple color of bar chart

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
df = pd.DataFrame([['CAT1',9,3,24,46,76], ['CAT2', 48,90,42,56,68], ['CAT3', 31,24,28,11,90],
                   ['CAT4', 76,85,16,65,91]],
                  columns=['metric', 'A', 'B', 'C', 'D', 'E'])
                  
df.plot(
        kind='bar',
        stacked=False
        )

plt.legend(labels=['A', 'B', 'C', 'D', 'E'], ncol=4, loc='center', fontsize=15, bbox_to_anchor=(0.5, 1.06))

plt.show()

enter image description here

CodePudding user response:

By default, matplotlib recognizes the index of your dataframe as x-labels. I suggest you to add the following to make the column metric as the index, which allows matplotlib to automatically add label for you.

df = df.set_index('metric')
  • Related