Python 在 Seaborn Barplot 上标记轴
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31632637/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Label axes on Seaborn Barplot
提问by Erin Shellman
I'm trying to use my own labels for a Seaborn barplot with the following code:
我正在尝试使用以下代码为 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')
However, I get an error that:
但是,我收到一个错误:
AttributeError: 'AxesSubplot' object has no attribute 'set_axis_labels'
What gives?
是什么赋予了?
采纳答案by sascha
Seaborn's barplot returns an axis-object (not a figure). This means you can do the following:
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()
回答by Steffi Keran Rani J
One can avoid the AttributeError
brought about by set_axis_labels()
method by using the matplotlib.pyplot.xlabel
and matplotlib.pyplot.ylabel
.
可以通过使用and来避免方法AttributeError
带来set_axis_labels()
的。matplotlib.pyplot.xlabel
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.
matplotlib.pyplot.xlabel
设置 x 轴标签,同时matplotlib.pyplot.ylabel
设置当前轴的 y 轴标签。
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:
输出图:
回答by John R
You can also set the title of your chart by adding the title parameter as follows
您还可以通过添加标题参数来设置图表的标题,如下所示
ax.set(xlabel='common xlabel', ylabel='common ylabel', title='some title')