简体   繁体   English

Seaborn:如何在条形图中用 X 轴中的文本替换索引?

[英]Seaborn: How to replace index with text in X-Axis in barplot?

I have a dataset with category column which has integer values representing class label ie 0,1,2.....我有一个带有category列的数据集,它具有表示类标签的整数值,即 0,1,2.....

I have separate file which contains text labels for that category ie against index 0, it contains classA and so on.我有单独的文件,其中包含该类别的文本标签,即针对索引 0,它包含classA等等。 I want to plot a barplot using seaborn with following code.我想使用 seaborn 和以下代码绘制条形图。

import seaborn as sns
train_df = pd.read_csv("unclean_text.csv", sep='\t')
label_text = pd.read_csv("labels.csv")
is_dup = train_df['category'].value_counts()

plt.figure(figsize=(8,4))
sns.barplot(is_dup.index, is_dup.values, alpha=0.8, color=color[1])
plt.show()

It correctly plots the barplot for frequency of each class.它正确地绘制了每个类别频率的条形图。

在此处输入图片说明

But I want text labels on the x-axis instead of index values that are in label_text , which is also a column vector of length 19 (0-18).但我想要 x 轴上的文本标签,而不是label_text的索引值,它也是长度为 19 (0-18) 的列向量。 How to do it?怎么做?

sns.barplot() will return the axis for the plot. sns.barplot()将返回绘图的轴。 You can use this to set your tick labels: 您可以使用它来设置您的刻度标签:

import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns

color = ['r', 'g', 'b']
train_df = pd.read_csv("unclean_text.csv", sep='\t')
label_text = pd.read_csv("labels.csv")
is_dup = train_df['category'].value_counts()

plt.figure(figsize=(8,4))
ax = sns.barplot(is_dup.index, is_dup.values, alpha=0.8, color=color[1])
ax.set_xlabel('Category')
ax.set_ylabel('Number of Occurrences')
ax.set_xticklabels(label_text['labels'], rotation='vertical', fontsize=10)
plt.show()

This assumes labels.csv is something like: 假设labels.csv是这样的:

labels
cat0
cat1
cat2
cat3
cat4
cat5
cat6
cat7
cat8

etc..

Giving you an output: 给你一个输出:

带x轴标签的图形图

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

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