简体   繁体   中英

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

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()

在此处输入图像描述

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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM