Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

seaborn

I have a dataset with category column which has integer values representing class label i.e 0,1,2.....

I have separate file which contains text labels for that category i.e against index 0, it contains classA and so on. I want to plot a barplot using seaborn with following code.

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.

enter image description here

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). How to do it?

like image 716
Haroon S. Avatar asked Aug 17 '17 08:08

Haroon S.


People also ask

How do I remove the x-axis labels in Seaborn?

To hide or remove X-axis labels, use set(xlabel=None). To display the figure, use show() method.

How do you show data labels in Seaborn barplot?

In seaborn barplot with bar, values can be plotted using sns. barplot() function and the sub-method containers returned by sns. barplot(). Import pandas, numpy, and seaborn packages.


1 Answers

sns.barplot() will return the axis for the plot. 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
cat0
cat1
cat2
cat3
cat4
cat5
cat6
cat7
cat8

etc..

Giving you an output:

graph plot with labels for x axis

like image 184
Martin Evans Avatar answered Oct 12 '22 12:10

Martin Evans