2017-08-09 56 views
2

我怎樣纔能有相同的圖例出現在2個子圖上並使其擴展到2?是否有人知道,如果我必須分別爲每個子圖精確標記y(如果它是相同的)情節是爲了科學論文)?我知道後一個問題與計算無關,但如果有人知道答案,我將不勝感激。擴展的圖例超過2個子圖

因爲我用的傳奇位置:

 ax[0].legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3, 
       ncol= 4, mode="expand", borderaxespad=0) 

plots

+0

這是一個matplolib問題? –

+0

是的。這不適合這個論壇嗎? – Tassou

+0

很適合。它可能會通過matplotlib標籤獲得更多答案。我會添加它。 –

回答

1

爲了使各次要情節都傳說舒展,你需要調整給bbox_to_anchor座標。對於寬度(第三個參數),使用2.2覆蓋圖的寬度加上子圖之間的間距的2倍。 (如果你有不同的間距比默認的,像f.tightlayout(),該值將需要調整。)

這裏有一個簡單的工作示例:

import numpy as np 
import matplotlib.pyplot as plt 

x1 = np.linspace(0.0, 2.0) 
x2 = np.linspace(0.0, 2.0) 

y1 = np.cos(2 * np.pi * x1) * np.exp(-x1) 
y2 = np.cos(2 * np.pi * x2) 

f,ax = plt.subplots(1, 2) 

ax[0].plot(x1, y1, 'ko-', label='Damped') 
ax[0].plot(x2, y2, 'r.-', label='Undamped') 
ax[1].plot(x1, y1, 'ko-', label='Damped') 
ax[1].plot(x2, y2, 'r.-', label='Undamped') 

ax[0].legend(bbox_to_anchor=(0., 1.02, 2.2, .102), loc=3, 
       ncol=4, mode="expand", borderaxespad=0) 

plt.show() 

結果是這樣的情節:

enter image description here

+0

謝謝,那正是我所需要的 – Tassou

1

要在圖中的所有子圖上拉伸圖例,可以半自動化圖例佈局。使用圖中的subplotpars可以找到使用的間距,這樣可以直接在bbox_to_anchor參數中使用這些間距。這需要通過參數bbox_transform將圖例變換設置爲圖形變換。您需要手動指定的唯一參數是軸和圖例之間的間距(以下示例中爲0.02)和圖例高度(以下示例中爲0.05),兩者均以圖形高度爲單位。

s = fig.subplotpars 
bb=[s.left, s.top+0.02, s.right-s.left, 0.05 ] 
leg = axes[0].legend(..., bbox_to_anchor=bb, mode="expand", borderaxespad=0, 
        bbox_transform=fig.transFigure) 

完整的例子:

import matplotlib.pyplot as plt 
import numpy as np 

a = np.cumsum(np.random.rand(10,8), axis=0) 

fig, axes = plt.subplots(ncols=2) 

for i in range(a.shape[1]): 
    axes[i//4].plot(a[:,i], marker="s", label="Label {}".format(i)) 

s = fig.subplotpars 
bb=[s.left, s.top+0.02, s.right-s.left, 0.05 ] 
leg = axes[0].legend(loc=8, bbox_to_anchor=bb, ncol= 4, mode="expand", borderaxespad=0, 
       bbox_transform=fig.transFigure, fancybox=False, edgecolor="k") 
leg.get_frame().set_linewidth(72./fig.dpi) 
plt.show() 

enter image description here

至於是否需要一個或兩個傳說中的一篇科學論文,這是完全dependend紙張的風格。我猜想使用像這樣的單個傳說很好。然而,期刊大多要求您用小寫字母標記每個子區塊,如ab(a)(b)