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

时间:2019-08-09 20:51:42

标签: python matplotlib

我试图在轴的右侧添加一个附加的轴标签,但既不想打勾,也不想打勾标签。

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

1 个答案:

答案 0 :(得分:1)

我不会为此而滥用辅助轴。只需将标签放在右侧并使其可见即可。

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