如何在matplotlib中添加额外的yaxis标签

2024-10-03 04:36:05 发布

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

我正在尝试在轴的右侧添加一个额外的轴标签,但不需要记号或记号标签。你知道吗

import pandas as pd
import matplotlib.pyplot as plt

fig, axs = plt.subplots(2,2,sharey=True,sharex=True)
for i in range(2):
    for j in range(2):
        pd.Series(np.random.random(10)).plot(ax=axs[i,j])
        axs[0,j].set_title('j = {}'.format(j))
    ax[1,j].set_ylabel('x')
    secaxy = axs[i,1].secondary_yaxis('right')
    secaxy.set_ylabel('i = {}'.format(i))
    secaxy.set_yticks([])
    ax[i,0].set_ylabel('y')

出于某种原因,set_yticks([])不能代替记号。你知道吗

[In]: secaxy.get_yticks()
[Out:] array([-0.25,  0.  ,  0.25,  0.5 ,  0.75,  1.  ,  1.25])

有什么方便的方法可以在绘图的右侧获得一个没有刻度的附加轴标签?你知道吗

correct labels, but need to remove the ticks on the right


Tags: inimporttrueforasplt标签ax
1条回答
网友
1楼 · 发布于 2024-10-03 04:36:05

我不会滥用辅助轴。只要把标签放在右边,把它看出来就行了。你知道吗

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

fig, axs = plt.subplots(2,2,sharey=True,sharex=True) 
for i in range(2):
    for j in range(2):
        pd.Series(np.random.random(10)).plot(ax=axs[i,j])
for j in range(2):
    axs[0,j].set_title('j = {}'.format(j))
for i in range(2):
    axs[i,1].set_ylabel('i = {}'.format(i))
    axs[i,1].yaxis.get_label().set_visible(True)
    axs[i,1].yaxis.set_label_position("right")
    axs[i,0].set_ylabel('y')

plt.show()

enter image description here

相关问题 更多 >