在Seaborn的柱状图上标注坐标轴。

254
我正在尝试使用以下代码为Seaborn的条形图添加自定义标签:
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')

desired result

然而,我遇到了一个错误,错误信息如下:
AttributeError: 'AxesSubplot' object has no attribute 'set_axis_labels'

为什么我会收到这个错误?
6个回答

404

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

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

10
seaborn没有自己的方法来设置这些内容 - 无需涉及matplotlib吗? - WestCoastProjects
所以一般规则是 FacetGrid 或任何分面返回一个图形对象,而其他所有内容都返回一个轴对象? - alexpghayes

73
通过使用matplotlib.pyplot.xlabelmatplotlib.pyplot.ylabel方法,可以避免由set_axis_labels()方法引起的AttributeError错误。 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)

输出结果:

在此输入图片描述


我认为应该只是plt.show(fig)。它给了我TypeError:show()需要1个位置参数,但提供了2个。只有plt.show()才能给我想要的结果。 - Joe Ferndz
这样单独进行操作的另一个优点是可以指定其他杂项 matplotlib.text.Text 属性。我最常用它来指定我们组织使用的自定义字体,方法是将 fontproperties 设置为 TTF 文件的位置。 - Neelotpal Shukla

45
您可以通过添加以下标题参数来设置图表的标题。
ax.set(xlabel='common xlabel', ylabel='common ylabel', title='some title')

ax.set() 中是否有一种方法可以改变标签和标题的字体大小? - rahul-ahuja

8

另一种方法是直接在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("Colors")
ax.set_ylabel("Values")

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

输出:

在这里输入图片描述


0

轴标签是列名,因此您可以在barplot调用中重命名(或set_axis)列:

fake = pd.DataFrame({'cat': ['red', 'green', 'blue'], 'val': [1, 2, 3]})
sns.barplot(x='Values', y='Colors', 
            data=fake.rename(columns={'cat': 'Colors', 'val': 'Values'}), 
            #data=fake.set_axis(['Colors', 'Values'], axis=1), 
            color='black');

另一种方法是,由于barplot返回Axes对象,因此您可以将set调用链接到它上面。
sns.barplot(x='val', y='cat', data=fake, color='black').set(xlabel='Values', ylabel='Colors', title='My Bar Chart');

res


如果数据是一个pandas对象,那么pandas有一个plot方法,可以传递很多选项,包括标题、轴标签和figsize。
fake.plot(y='val', x='cat', kind='barh', color='black', width=0.8, legend=None,
          xlabel='Colors', ylabel='Values', title='My Bar Chart', figsize=(12,5));

0
你遇到的关于set_axis_labels的错误是因为在Seaborn的AxesSubplot对象中没有这样的函数。要解决这个问题,你可以使用Seaborn的barplot返回的Matplotlib axes对象提供的set_xlabel()set_ylabel()方法。下面是具体操作步骤:
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')

# Set custom axis labels
fig.get_xaxis().set_label_text('Values')
fig.get_yaxis().set_label_text('Colors')
plt.show()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接