Home > OS >  How to add x-axis tick labels in python bar chart
How to add x-axis tick labels in python bar chart

Time:05-02

I am trying to plot a python bar chart. Here is my code and an image of my bar chart. The problems I am facing are:

  1. I want to write name of each category of bar chart on the x-axis as CAT1, CAT2, CAT3, CAT4. Right now it's printing 0, 1, 2 on the x-axis.

  2. I want to change the purple color of the 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