我试图在条形图上绘制一个折线图,但刻度和点的实际位置都没有对齐。我希望它们对齐。(请注意,我将在另一侧绘制另一组类似(但反向)的数据,因此是子图。)
这是我到目前为止所拥有的
import matplotlib.pyplot as plt
import numpy as np
group = [0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55]
amount1 = [967, 975, 1149, 1022, 852, 975, 1025, 1134, 994, 1057, 647, 1058]
amount2 = [286, 364, 111, 372, 333, 456, 258, 152, 400, 181, 221, 441]
f, (ax1, ax2) = plt.subplots(nrows = 1, ncols = 2, sharey=True, figsize = (17,8))
ax1_2 = ax1.twinx()
# y_pos
y_pos = np.arange(len(group))
# plot men
ax1.barh(y_pos, amount1, align = 'center')
ax1_2.plot(amount2, group, color = 'black', marker = 'o')
# ticks
ax1.set_yticks(y_pos)
ax1.set_yticklabels(group)
ax1.invert_xaxis()
ax1.yaxis.tick_right()
# padding
plt.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=0.05, hspace=None)
plt.show()
plt.close()
我试过设置刻度,但条形图和线形图的概念似乎非常不同。我也尝试在ax1上绘制这两个图形,但是线图远远超出了条形图,它们根本没有对齐。我也尝试过ax1_2.set_yticks(ax1.get_yticks())
,但这也有类似的问题
任何帮助都将不胜感激
主要问题是两个轴的
ylim
没有对齐。barh
图的y
类似于0、1、2、3到11。直线图的y
在5步中从0变为55。要对齐它们,只需执行ax1_2.set_ylim([y * 5 for y in ax1.get_ylim()])
另一种方法是也将
ypos
用于折线图。然后可以简单地复制限制:ax1_2.set_ylim(ax1.get_ylim())
以下是示例代码,为了简单起见,省略了第二个图形:
现在,绘图的0、10、20刻度从
ax1_2
开始变暗。只需调用ax1_2.set_yticks([])
即可删除这些内容PS:还有另一种方法,就是忘记为单位测量
ypos
,只对ax1
的y轴使用group
。然后,需要调整杆的高度,例如,调整为4.5,因为现在以^{代码:
您可以在
ax1
中打印这两个变量,并删除y_pos
,因为在最后,它们都将group
变量作为y
坐标共享然后,您可以将
height
添加到barh图中这里是代码:
以及一个具有结果的图像:
相关问题 更多 >
编程相关推荐