简体   繁体   English

如何在 python 条形图中添加 x 轴刻度标签

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

I am trying to plot a python bar chart.我正在尝试 plot python 条形图。 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.我想在 x 轴上将每个条形图类别的名称写为 CAT1、CAT2、CAT3、CAT4。 Right now it's printing 0, 1, 2 on the x-axis.现在它在 x 轴上打印 0、1、2。

  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.默认情况下, matplotlib将您的 dataframe 的索引识别为 x 标签。 I suggest you to add the following to make the column metric as the index, which allows matplotlib to automatically add label for you.我建议你添加以下内容,使列metric成为索引,这样matplotlib就会自动为你添加 label。

df = df.set_index('metric')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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