右对齐水平 seaborn barplot
Right align horizontal seaborn barplot
如何使水平的 seaborn barplot 右对齐/镜像
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)
您只需更改 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()
函数
为了反转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()
如何使水平的 seaborn barplot 右对齐/镜像
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)
您只需更改 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()
函数
为了反转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()