如何使用 Matplotlib 对齐两个 y 轴刻度的网格线? [英] How do I align gridlines for two y-axis scales using Matplotlib?

查看:60
本文介绍了如何使用 Matplotlib 对齐两个 y 轴刻度的网格线?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在绘制 y 轴上具有不同单位的两个数据集.有没有办法让刻度线和网格线在两个 y 轴上对齐?

I'm plotting two datasets with different units on the y-axis. Is there a way to make the ticks and gridlines aligned on both y-axes?

第一张图展示了我得到的东西,第二张图展示了我想要得到的东西.

The first image shows what I get, and the second image shows what I would like to get.

这是我用来绘制的代码:

This is the code I'm using to plot:

import seaborn as sns
import numpy as np
import pandas as pd

np.random.seed(0)
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.plot(pd.Series(np.random.uniform(0, 1, size=10)))
ax2 = ax1.twinx()
ax2.plot(pd.Series(np.random.uniform(10, 20, size=10)), color='r')

推荐答案

我不确定这是否是最好的方法,但它确实用一行代码解决了:

I am not sure if this is the prettiest way to do it, but it does fix it with one line:

import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import pandas as pd

np.random.seed(0)
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.plot(pd.Series(np.random.uniform(0, 1, size=10)))
ax2 = ax1.twinx()
ax2.plot(pd.Series(np.random.uniform(10, 20, size=10)), color='r')

# ADD THIS LINE
ax2.set_yticks(np.linspace(ax2.get_yticks()[0], ax2.get_yticks()[-1], len(ax1.get_yticks())))

plt.show()

这篇关于如何使用 Matplotlib 对齐两个 y 轴刻度的网格线?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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