python怎么定义正方形函数_python – Matplotlib自定义图例以显示正方形而不是矩形...
這是我嘗試將條形圖的圖例從矩形更改為方形:
import matplotlib.patches as patches
rect1 = patches.Rectangle((0,0),1,1,facecolor='#FF605E')
rect2 = patches.Rectangle((0,0),1,1,facecolor='#64B2DF')
plt.legend((rect1, rect2), ('2016', '2015'))
但是當我繪制這個時,我仍然會看到矩形而不是正方形:
有關如何做到這一點的任何建議?
我嘗試了@ImportanceOfBeingErnest和@furas提供的兩種解決方案,結果如下:
@ ImportanceOfBeingErnest的解決方案是最容易做到的:
plt.rcParams['legend.handlelength'] = 1
plt.rcParams['legend.handleheight'] = 1.125
結果如下:
我的最終代碼如下所示:
plt.legend((df.columns[1], df.columns[0]), handlelength=1, handleheight=1) # the df.columns = the legend text
@ furas的解決方案產生了這個,我不知道為什么文本遠離矩形,但我確信差距可以以某種方式改變:
最佳答案:
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
不幸的是,提供相等的句柄長度= 1,handleheight = 1將不會提供完美的矩形.似乎handlelength = 1,handleheight = 1.125將完成這項工作,但這可能取決于所使用的字體.
另一種方法是,如果要使用代理藝術家,可以使用plot / scatter方法中的方形標記.
bar1 = plt.plot([], marker="s", markersize=15, linestyle="", label="2015")
并將其提供給圖例,圖例(手柄= [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()
生產
標簽:python,matplotlib
總結
以上是生活随笔為你收集整理的python怎么定义正方形函数_python – Matplotlib自定义图例以显示正方形而不是矩形...的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 内固定取出术后护理_股骨内固定钢板取出术
- 下一篇: 华为做raid5步骤_华为RH2288V