Seaborn Barplot上的标签轴


125

我正在尝试通过以下代码将自己的标签用于Seaborn barplot:

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

在此处输入图片说明

但是,我得到一个错误:

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

是什么赋予了?

Answers:


235

Seaborn的条形图返回一个轴对象(不是图形)。这意味着您可以执行以下操作:

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

2
seaborn没有自己的方式来设置这些-不涉及matplotlib
javadba

因此,一般规则是FacetGrid/刻面返回图形对象,其他所有返回轴对象?
alexpghayes

27

使用和可以避免方法AttributeError带来的麻烦。set_axis_labels()matplotlib.pyplot.xlabelmatplotlib.pyplot.ylabel

matplotlib.pyplot.xlabel设置x轴标签,而matplotlib.pyplot.ylabel设置当前轴的y轴标签。

解决方案代码:

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)

输出图:

在此处输入图片说明


13

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

ax.set(xlabel='common xlabel', ylabel='common ylabel', title='some title')
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.