matplotlib对齐twinx刻度线 [英] matplotlib align twinx tick marks

查看:300
本文介绍了matplotlib对齐twinx刻度线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以绘制两个独立的y轴以使刻度线对齐?

Is it possible to make a plot with two independent y-axes such that the tick marks align?

下面是解决方案一半的示例.我已经使用twinx将y轴加倍,但是刻度线未对齐,并且网格线在绘图上形成了一个尴尬的图案.有没有一种方法可以使刻度线共享相同的位置,但对应于不同的y值?在下面的示例中,我希望左侧的5的刻度线与右侧的6的刻度线处于相同的垂直位置.

Below is an example of half of the solution. I've doubled the y-axis using twinx, but the tick marks aren't aligned and the gridlines form an awkward pattern on the plot. Is there a way to make the tick marks share the same positions, but correspond to different y-values? In the example below, I would like the tick mark for 5 on the left to be at the same vertical position as the tick mark for 6 on the right.

import numpy as np

a = np.random.normal(10, 3, size=20)
b = np.random.normal(20, 5, size=40)

fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
ax1.hist(a)
ax2.hist(b)

此练习的总体要点是使两条轴线的网格线重叠.

The overarching point of this exercise is to make the grid lines overlap for the two axes.

推荐答案

您需要手动设置yticks,因为这些值是自动计算得出的.添加类似这样的内容:

You need to manually set the yticks as it stands these are automatically calculated resulting in a variation. Adding something like this:

ax1.set_yticks(np.linspace(ax1.get_ybound()[0], ax1.get_ybound()[1], 5))
ax2.set_yticks(np.linspace(ax2.get_ybound()[0], ax2.get_ybound()[1], 5))

我们在轴的边界之间使用5个点的数组来设置ytick位置.由于您具有直方图,因此可以将每种情况下的下限值都设置为零,并且您可能希望将上限值稍大一些,所以我宁可拥有

where we set the ytick locations using an array of 5 points between the bounds of the axis. Since you have a histogram you could just set the lower value to zero in each case, and you may want to have the upper bound somewhat larger, so I would instead have

ax1.set_yticks(np.linspace(0, ax1.get_ybound()[1]+1, 5))
ax2.set_yticks(np.linspace(0, ax2.get_ybound()[1]+1, 5))

提供图表(为了清楚起见,颜色和透明度(alpha)有所变化):

Giving a plot (with a change of color and transparency (alpha) for clarity):

这篇关于matplotlib对齐twinx刻度线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆