Matplotlib提供rcParams
legend.handlelength : 2. # the length of the legend lines in fraction of fontsize
legend.handleheight : 0.7 # the height of the legend handle in fraction of fontsize
你可以設置呼叫內plt.legend()
plt.legend(handlelength=1, handleheight=1)
或使用rcParams在腳本的開頭
import matplotlib
matplotlib.rcParams['legend.handlelength'] = 1
matplotlib.rcParams['legend.handleheight'] = 1
不幸的是提供平等handlelength=1, handleheight=1
不會給一個完美的rectange。看來handlelength=1, handleheight=1.125
會完成這項工作,但這可能取決於正在使用的字體。
另一種方法是,如果要使用代理藝術家,可以使用plot/scatter方法中的方形標記。
bar1 = plt.plot([], marker="s", markersize=15, linestyle="", label="2015")
並將其提供給圖例legend(handles=[bar1])
。使用這種方法需要設置matplotlib.rcParams['legend.numpoints'] = 1
,否則兩個標記將出現在圖例中。
下面是兩種方法
import matplotlib.pyplot as plt
plt.rcParams['legend.handlelength'] = 1
plt.rcParams['legend.handleheight'] = 1.125
plt.rcParams['legend.numpoints'] = 1
fig, ax = plt.subplots(ncols=2, figsize=(5,2.5))
# Method 1: Set the handlesizes already in the rcParams
ax[0].set_title("Setting handlesize")
ax[0].bar([0,2], [6,3], width=0.7, color="#a30e73", label="2015", align="center")
ax[0].bar([1,3], [3,2], width=0.7, color="#0943a8", label="2016", align="center")
ax[0].legend()
# Method 2: use proxy markers. (Needs legend.numpoints to be 1)
ax[1].set_title("Proxy markers")
ax[1].bar([0,2], [6,3], width=0.7, color="#a30e73", align="center")
ax[1].bar([1,3], [3,2], width=0.7, color="#0943a8", align="center")
b1, =ax[1].plot([], marker="s", markersize=15, linestyle="", color="#a30e73", label="2015")
b2, =ax[1].plot([], marker="s", markersize=15, linestyle="", color="#0943a8", label="2016")
ax[1].legend(handles=[b1, b2])
[a.set_xticks([0,1,2,3]) for a in ax]
plt.show()
一個完整的例子生產
Concverning的最後一個點的位置:在解決方案從@furas它使用傳統的handler_map補丁改變是二次。然而,與矩形(因此更寬)的補丁相比,文本的填充保持不變。默認情況下,這個填充是'0.8',但你可以像使用'plt.rcParams ['legend.handletextpad'] = 0'這樣使用rcParams來設置它來減少間距。在這種情況下,你可能會設置一些負數,「-0.8」可能是不錯的選擇。 – ImportanceOfBeingErnest