Label axes on Seaborn Barplot

PythonMatplotlibSeaborn

Python Problem Overview


I'm trying to use my own labels for a Seaborn barplot with the following code:

import pandas as pd
import seaborn as sns
    
fake = pd.DataFrame({'cat': ['red', 'green', 'blue'], 'val': [1, 2, 3]})
fig = sns.barplot(x = 'val', y = 'cat', 
                  data = fake, 
                  color = 'black')
fig.set_axis_labels('Colors', 'Values')

enter image description here

However, I get an error that:

AttributeError: 'AxesSubplot' object has no attribute 'set_axis_labels'

What gives?

Python Solutions


Solution 1 - Python

Seaborn's barplot returns an axis-object (not a figure). This means you can do the following:

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

fake = pd.DataFrame({'cat': ['red', 'green', 'blue'], 'val': [1, 2, 3]})
ax = sns.barplot(x = 'val', y = 'cat', 
              data = fake, 
              color = 'black')
ax.set(xlabel='common xlabel', ylabel='common ylabel')
plt.show()

Solution 2 - Python

One can avoid the AttributeError brought about by set_axis_labels() method by using the matplotlib.pyplot.xlabel and matplotlib.pyplot.ylabel.

matplotlib.pyplot.xlabel sets the x-axis label while the matplotlib.pyplot.ylabel sets the y-axis label of the current axis.

Solution code:

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

fake = pd.DataFrame({'cat': ['red', 'green', 'blue'], 'val': [1, 2, 3]})
fig = sns.barplot(x = 'val', y = 'cat', data = fake, color = 'black')
plt.xlabel("Colors")
plt.ylabel("Values")
plt.title("Colors vs Values") # You can comment this line out if you don't need title
plt.show(fig)

Output figure:

enter image description here

Solution 3 - Python

You can also set the title of your chart by adding the title parameter as follows

ax.set(xlabel='common xlabel', ylabel='common ylabel', title='some title')

Solution 4 - Python

Another way of doing it, would be to access the method directly within the seaborn plot object.

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

fake = pd.DataFrame({'cat': ['red', 'green', 'blue'], 'val': [1, 2, 3]})
ax = sns.barplot(x = 'val', y = 'cat', data = fake, color = 'black')

ax.set_xlabel("Colors")
ax.set_ylabel("Values")

ax.set_yticklabels(['Red', 'Green', 'Blue'])
ax.set_title("Colors vs Values") 

Produces:

enter image description here

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionErin ShellmanView Question on Stackoverflow
Solution 1 - PythonsaschaView Answer on Stackoverflow
Solution 2 - PythonSteffi Keran Rani JView Answer on Stackoverflow
Solution 3 - PythonJohn RView Answer on Stackoverflow
Solution 4 - Pythonsimons____View Answer on Stackoverflow