如何使用Seaborn基于Pandas Series绘制水平条形图
解决Seaborn水平条形图绘制的TypeError问题
问题场景
我想用Seaborn水平绘制以下Pandas Series:
fruity -0.380938 hard -0.310382 pluribus -0.247448 nougat 0.199375 caramel 0.213416 crispedricewafer 0.324680 peanutyalmondy 0.406192 bar 0.429929 chocolate 0.636517 Name: winpercent, dtype: float64
试了这段代码:
ax = sns.barplot(win_corr.index, win_corr.values, orient='h') # win_corr是该Series的变量名 ax.set_ylabel('Pearson') ax.set_xlabel('') plt.title('Horizontal') ax.bar_label(ax.containers[0], fmt= '%0.1f' ) plt.show()
结果直接报错:
TypeError Traceback (most recent call last) <ipython-input-59-0e19fa0939fd> in <module>() ----> 1 ax = sns.barplot(win_corr.index, win_corr.values, orient='h') # win_corr是该Series的变量名 2 ax.set_ylabel('Pearson') 3 ax.set_xlabel('') 4 plt.title('Horizontal') 5 ax.bar_label(ax.containers[0], fmt= '%0.1f' ) 4 frames /usr/local/lib/python3.7/dist-packages/seaborn/_core.py in infer_orient(x, y, orient, require_numeric) 1336 elif str(orient).startswith("h"): 1337 if require_numeric and x_type != "numeric": -> 1338 raise TypeError(nonnumeric_dv_error.format("Horizontal", "x")) 1339 return "h" 1340 TypeError: Horizontal orientation requires numeric `x` variable.
不过垂直条形图能正常跑,代码是这样的:
ax = sns.barplot(win_corr.index, win_corr.values) ax.set_ylabel('pearson') ax.set_xlabel('Features') plt.title('Pearson') ax.bar_label(ax.containers[0], fmt= '%0.1f' ) plt.show()
想请教下要改哪些地方才能成功画出水平条形图?
问题根源
其实就是参数传反了!Seaborn的barplot对水平条形图的参数要求是:
x必须是数值型变量(你的win_corr.values)y必须是分类变量(你的win_corr.index)
你之前的代码把分类变量给了x,数值变量给了y,刚好和水平模式的要求相反,所以才会抛出那个“水平方向需要数值型x变量”的错误。而垂直条形图默认是x轴放分类、y轴放数值,所以你的代码能正常运行。
修复后的代码
只需要调换x和y的位置,用关键字参数明确指定会更清晰,避免再搞混:
import seaborn as sns import matplotlib.pyplot as plt # win_corr是你的目标Series ax = sns.barplot(x=win_corr.values, y=win_corr.index, orient='h') ax.set_xlabel('Pearson Correlation') # 现在x轴对应数值,标注相关系数 ax.set_ylabel('Features') # y轴对应分类的食物名称 plt.title('Horizontal Pearson Correlation') ax.bar_label(ax.containers[0], fmt='%0.3f') # 保留三位小数更精准 plt.show()
额外小优化
如果想让条形按照数值大小排序,看起来更直观,可以先对Series排序:
# 按数值从小到大排序 win_corr_sorted = win_corr.sort_values() ax = sns.barplot(x=win_corr_sorted.values, y=win_corr_sorted.index, orient='h')
内容的提问来源于stack exchange,提问作者Ahmad
相关产品推荐
相关产品推荐

