【问题标题】:Right align horizontal seaborn barplot右对齐水平 seaborn 条形图
【发布时间】:2021-08-20 07:20:45
【问题描述】:
如何使水平 seaborn 条形图右对齐/镜像
import matplotlib.pyplot as plt
import seaborn as sns
x = ['x1', 'x2', 'x3']
y = [4, 6, 3]
sns.barplot(x=y, y=x, orient='h')
plt.show()
默认的水平条形图如下所示
我想要这样的东西(带有适当的 xticks)
【问题讨论】:
标签:
python
matplotlib
plot
seaborn
data-visualization
【解决方案1】:
为了反转x轴,你可以使用:
ax.invert_xaxis()
然后,为了将标签向右移动,您可以使用:
plt.tick_params(axis = 'y', left = False, right = True, labelleft = False, labelright = True)
或者,更短:
ax.yaxis.tight_right()
完整代码
import matplotlib.pyplot as plt
import seaborn as sns
x = ['x1', 'x2', 'x3']
y = [4, 6, 3]
ax = sns.barplot(x=y, y=x, orient='h')
ax.invert_xaxis()
ax.yaxis.tick_right()
plt.show()
【解决方案2】:
您可以只更改matplotlib x 轴限制。一种简单的方法是捕获sns.barplot 返回的Axes 实例,然后在其上使用ax.set_xlim。
然后您可以使用ax.yaxis.set_label_position('right') 和ax.yaxis.set_ticks_position('right') 将刻度和轴标签向右移动。
例如:
import matplotlib.pyplot as plt
import seaborn as sns
x = ['x1', 'x2', 'x3']
y = [4, 6, 3]
ax = sns.barplot(x=y, y=x, orient='h')
ax.set_xlim(ax.get_xlim()[1], ax.get_xlim()[0])
ax.yaxis.set_label_position('right')
ax.yaxis.set_ticks_position('right')
plt.show()
在那个例子中,我抓住了现有的限制,只是扭转了它们。或者,您可以明确设置它们,确保第一个数字是上限,以确保反向比例。例如:
ax.set_xlim(6.5, 0)
最后一种选择是使用内置的ax.invert_xaxis() 函数