我试图使用我自己的标签为一个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'
到底发生了什么事?
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()
可以通过使用matplotlib.pyplot.xlabel和matplotlib.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)
输出图:
另一种方法是直接在seaborn plot对象中访问该方法。
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")
生产: