簡體   English   中英

Seaborn Barplot上的標簽軸

[英]Label axes on Seaborn Barplot

我正在嘗試使用我自己的標簽來制作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')

在此輸入圖像描述

但是,我得到一個錯誤:

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

輸出數字:

在此輸入圖像描述

您還可以通過添加title參數來設置圖表的標題,如下所示

ax.set(xlabel='common xlabel', ylabel='common ylabel', title='some title')

你剛用fig.set_axis_labels()犯了一個錯誤

遵循最佳解決方案

import pandas as pd # for data anlisys
import seaborn as sns # for data visualization
import matplotlib.pyplot as plt # for data visualization

fake = pd.DataFrame({'cat': ['red', 'green', 'blue'], 'val': [1, 2, 3]})
fig = sns.barplot(x = 'val', y = 'cat', 
                  data = fake, 
                  color = 'black')

plt.title("Barplot of Values and Colors", fontsize = 20)
plt.xlabel("Values", fontsize = 15)
plt.ylabel("Colors", fontsize = 15)
plt.show()

點擊這里查看輸出

你也可以使用

fig.set(title = "Barplot of Values and Colors",
        xlabel = "Values",
        ylabel = "Colors")

謝謝

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM