在matplotlib中使用停用的网格将Ytick恢复到成对的yaxis上

2024-06-06 10:54:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我在一个子地块上绘制直线,其中每个子地块都有一个成对的y轴。 问题在于,使用以下matplotlib样式表会为两个成对垂直(y-)轴创建自动水平网格,这两个轴不匹配

# * Set the matplotlib.pyplot default template (plotting style and background) *
mpl_plt_default_template = 'seaborn-whitegrid'
plt.style.use(mpl_plt_default_template)

初始输出图形如下所示: enter image description here

如您所见,生成了两个不重叠的网格

我试图在制作时关闭孪生轴的网格(在右侧) 可见yaxis滴答声,但到目前为止没有效果

我使用的代码如下:

# * Standard procedure of making the axis-ticks visible
# 1) Making ticks visible generally
ax.yaxis.majorTicks[0].tick1line.set_visible(True)
# 2) More in-depth tick-handling via the "runtime configuration parameters" ("rc params")
# of matplotlib
plt.rcParams.update({
    "ytick.direction": "out",  # direction: in, out, or inout
    "ytick.minor.visible": False,  # visibility of minor ticks on y-axis
    "ytick.major.left": True,   # draw y axis left major ticks
    "ytick.major.right": True   # draw y axis right major ticks
})

# i) Y-axis on the right-hand side
if twinned_axis:
    # NOTE on scope: Set left to False, right to True
    plt.rcParams.update({
        'ytick.left': False,
        "ytick.labelleft": False,
        'ytick.right': True,
        "ytick.labelright": True
    })
# ii) Standard case: y-axis on the left-hand side
else:
    # NOTE on scope: Set right to False, left to True
    plt.rcParams.update({
        'ytick.left': True,
        "ytick.labelleft": True,
        'ytick.right': False,
        "ytick.labelright": False
        })

我得到的结果可以在下图中看到。 不幸的是,记号仍然丢失,只有标签在孪生轴上可见。 enter image description here


Tags: thetorightfalsetrue网格matplotlibon
1条回答
网友
1楼 · 发布于 2024-06-06 10:54:52

这不是孪生轴的问题,在seaborn-whitegrid模板ticks'大小设置为0.0时,检查它here。因此,您需要在rcParams中更改其大小:

import numpy as np
import matplotlib.pyplot as plt


mpl_plt_default_template = 'seaborn-whitegrid'
plt.style.use(mpl_plt_default_template)

# set size value for major ticks
plt.rcParams['xtick.major.size'] = 5
plt.rcParams['ytick.major.size'] = 5

f, ax1 = plt.subplots()

ax2 = ax1.twinx()
ax2.set_ylim((0.25, 1.5))

# turn off the twinned grid
ax2.yaxis.grid(False)

之前:

before

之后:

after

相关问题 更多 >