Eri*_*man 95 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')
Run Code Online (Sandbox Code Playgroud)
但是,我得到一个错误:
AttributeError: 'AxesSubplot' object has no attribute 'set_axis_labels'
Run Code Online (Sandbox Code Playgroud)
是什么赋予了?
sas*_*cha 177
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()
Run Code Online (Sandbox Code Playgroud)
小智 30
您还可以通过添加标题参数来设置图表的标题,如下所示
ax.set(xlabel='common xlabel', ylabel='common ylabel', title='some title')
Run Code Online (Sandbox Code Playgroud)
Ste*_*i J 18
通过使用和可以避免方法AttributeError带来set_axis_labels()的.matplotlib.pyplot.xlabelmatplotlib.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)
Run Code Online (Sandbox Code Playgroud)
输出数字:
小智 10
另一种方法是直接在 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("Colors")
ax.set_ylabel("Values")
ax.set_yticklabels(['Red', 'Green', 'Blue'])
ax.set_title("Colors vs Values")
Run Code Online (Sandbox Code Playgroud)
生产:
| 归档时间: |
|
| 查看次数: |
151215 次 |
| 最近记录: |