简体   繁体   中英

Label axes on Seaborn Barplot

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

在此输入图像描述

However, I get an error that:

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

What gives?

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

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:

在此输入图像描述

您还可以通过添加title参数来设置图表的标题,如下所示

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

You just maked a single mistake using fig.set_axis_labels()

follow the best solution

import pandas as pd # for data anlisys
import seaborn as sns # for data visualization
import matplotlib.pyplot as plt # for data visualization

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

plt.title("Barplot of Values and Colors", fontsize = 20)
plt.xlabel("Values", fontsize = 15)
plt.ylabel("Colors", fontsize = 15)
plt.show()

click here to see output

You can also use

fig.set(title = "Barplot of Values and Colors",
        xlabel = "Values",
        ylabel = "Colors")

Thank you

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