簡體   English   中英

右側的 matplotlib y 軸標簽

[英]matplotlib y-axis label on right side

有沒有一種簡單的方法可以將 y 軸標簽放在圖的右側? 我知道這可以使用ax.yaxis.tick_right()為刻度標簽完成,但我想知道是否也可以為軸標簽完成。

想到的一個想法是使用

ax.yaxis.tick_right()
ax2 = ax.twinx()
ax2.set_ylabel('foo')

但是,這不會產生將所有標簽(刻度和軸標簽)放在右側,同時保留 y 軸范圍的預期效果。 簡而言之,我想要一種將所有 y 軸標簽從左向右移動的方法。

看起來你可以這樣做:

ax.yaxis.set_label_position("right")
ax.yaxis.tick_right()

有關示例,請參見此處

如果您想按照matplotlib給出的示例並在軸的兩側創建一個帶有標簽的圖形,但不必使用subplots()函數,這是我的解決方案:

from matplotlib import pyplot as plt
import numpy as np

ax1 = plt.plot()
t = np.arange(0.01, 10.0, 0.01)
s1 = np.exp(t)
plt.plot(t,s1,'b-')
plt.xlabel('t (s)')
plt.ylabel('exp',color='b')

ax2 = ax1.twinx()
s2 = np.sin(2*np.pi*t)
ax2.plot(t, s2, 'r.')
plt.ylabel('sin', color='r')
plt.show()

以前的答案已經過時了。 以下是上述示例的最新代碼:

import numpy as np
import matplotlib.pyplot as plt

t = np.arange(0.01, 10.0, 0.01)
data1 = np.exp(t)
data2 = np.sin(2 * np.pi * t)

fig, ax1 = plt.subplots()

color = 'tab:red'
ax1.set_xlabel('time (s)')
ax1.set_ylabel('exp', color=color)
ax1.plot(t, data1, color=color)
ax1.tick_params(axis='y', labelcolor=color)

ax2 = ax1.twinx()  # instantiate a second axes that shares the same x-axis

color = 'tab:blue'
ax2.set_ylabel('sin', color=color)  # we already handled the x-label with ax1
ax2.plot(t, data2, color=color)
ax2.tick_params(axis='y', labelcolor=color)

fig.tight_layout()  # otherwise the right y-label is slightly clipped
plt.show()

這里開始

(對不起,我復活了這個問題)

我知道這是一個骯臟的技巧,但如果您不想深入處理軸並停留在plt命令中,您可以使用labelpad標量參數將標簽定位到圖形右側。 經過一些試驗和錯誤后工作,確切的標量值可能 (?) 與您的圖形大小的尺寸有關。

例子:

# move ticks
plt.tick_params(axis='y', which='both', labelleft=False, labelright=True)

# move label
plt.ylabel('Your label here', labelpad=-725, fontsize=18)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM