matplotlib中从右到左的水平条形图

店主

此处提供的示例代码生成此图:

在此处输入图片说明

我想知道是否有可能绘制出完全相同但“镜像”的东西,如下所示:

在此处输入图片说明

以下是提供的示例代码,以防链接停止工作:

import matplotlib.pyplot as plt
import numpy as np

# Fixing random state for reproducibility
np.random.seed(19680801)


plt.rcdefaults()
fig, ax = plt.subplots()

# Example data
people = ('Tom', 'Dick', 'Harry', 'Slim', 'Jim')
y_pos = np.arange(len(people))
performance = 3 + 10 * np.random.rand(len(people))
error = np.random.rand(len(people))

ax.barh(y_pos, performance, xerr=error, align='center',
        color='green', ecolor='black')
ax.set_yticks(y_pos)
ax.set_yticklabels(people)
ax.invert_yaxis()  # labels read top-to-bottom
ax.set_xlabel('Performance')
ax.set_title('How fast do you want to go today?')

plt.show()
谢尔多雷

你很亲密,你忘了放ax.invert_xaxis()但是,您仍然在左侧y轴上分配了y标记。

要在右侧分配刻度线,您需要首先创建一个双x轴(右侧y轴)实例(在此处ax1),然后在其上绘制条形图。您可以通过来隐藏左侧的y轴刻度和标签[]

我提供了两种解决方法(其余代码保持不变,只是现在您使用ax1代替ax

解决方案1

ax.set_yticklabels([]) # Hide the left y-axis tick-labels
ax.set_yticks([]) # Hide the left y-axis ticks
ax1 = ax.twinx() # Create a twin x-axis
ax1.barh(y_pos, performance, xerr=error, align='center',
    color='green', ecolor='black') # Plot using `ax1` instead of `ax`
ax1.set_yticks(y_pos)
ax1.set_yticklabels(people)

解决方案2(相同的输出):将绘图保留在左轴(ax)上,将x轴反转,然后将y-ticklabel设置为ax1

ax.invert_yaxis()  # labels read top-to-bottom
ax.invert_xaxis()  # labels read top-to-bottom

ax2 = ax.twinx()
ax2.set_ylim(ax.get_ylim())
ax2.set_yticks(y_pos)
ax2.set_yticklabels(people)

在此处输入图片说明

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章