Seaborn Barplot上的标签轴

时间:2015-07-26 01:08:48

标签: python matplotlib seaborn

我正在尝试将自己的标签用于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')

enter image description here

但是,我收到一个错误:

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

是什么给出了?

3 个答案:

答案 0 :(得分:140)

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

答案 1 :(得分:13)

使用 AttributeError set_axis_labels() ,可以避免matplotlib.pyplot.xlabel方法带来的matplotlib.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)

输出数字:

enter image description here

答案 2 :(得分:1)

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

ax.set(xlabel='common xlabel', ylabel='common ylabel', title='some title')
相关问题