简体   繁体   English

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

[英]How to add an extra y-axis label in matplotlib

I'm trying to add an additional axis label on the right side of an axis, but don't want ticks nor tick labels.我正在尝试在轴的右侧添加一个额外的轴标签,但不想要刻度或刻度标签。

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')

For some reason the set_yticks([]) doesn't replace the ticks.出于某种原因, set_yticks([])不会替换刻度。

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

What would be a convenient way to get an additional axis label on the right side of the plot without ticks?在没有刻度的情况下,在图的右侧获得附加轴标签的便捷方法是什么?

正确的标签,但需要删除右边的勾号

I wouldn't misuse a secondary axes for that.我不会为此滥用辅助轴。 Just put the label to the right and turn it visible.只需将标签放在右侧并使其可见。

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()

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM