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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 10:19:42  来源:igfitidea点击:

Label axes on Seaborn Barplot

pythonmatplotlibseaborn

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

enter image description here

在此处输入图片说明

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 AttributeErrorbrought about by set_axis_labels()method by using the matplotlib.pyplot.xlabeland matplotlib.pyplot.ylabel.

可以通过使用and来避免方法AttributeError带来set_axis_labels()的。matplotlib.pyplot.xlabelmatplotlib.pyplot.ylabel

matplotlib.pyplot.xlabelsets the x-axis label while the matplotlib.pyplot.ylabelsets 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:

输出图:

enter image description here

在此处输入图片说明

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