2 回答

TA貢獻1951條經驗 獲得超3個贊
圖例與邊界框邊緣的距離由borderaxespad參數設置。的borderaxespad是在字體大小的倍數為單位-使它自動獨立的軸尺寸。所以在這種情況下,
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(5)
y = np.random.randn(5)
fig, ax = plt.subplots(constrained_layout=True)
ax.plot(x, y, label='data1')
ax.plot(x, y-1, label='data2')
legend = ax.legend(loc="upper center", bbox_to_anchor=(0.5,0), borderaxespad=2)
plt.show()
在軸圖形底部的地方標題中提出了一個類似的問題,即在軸下方以恒定距離顯示標題?

TA貢獻1871條經驗 獲得超13個贊
您可以使用畫布的調整大小事件來更新bbox_to_anchor每次更新時的值。要計算新值,您可以使用軸變換 ( Bbox.inverse_transformed(ax.transAxes))的逆變換,它將以像素為單位的屏幕坐標轉換為 .x 中通常使用的軸坐標bbox_to_anchor。
這是一個支持將圖例放在軸的所有四個邊上的示例:
import numpy as np
from matplotlib import pyplot as plt
from matplotlib.transforms import Bbox
class FixedOutsideLegend:
"""A legend placed at a fixed offset (in pixels) from the axes."""
def __init__(self, ax, location, pixel_offset, **kwargs):
self._pixel_offset = pixel_offset
self.location = location
if location == 'right':
self._loc = 'center left'
elif location == 'left':
self._loc = 'center right'
elif location == 'upper':
self._loc = 'lower center'
elif location == 'lower':
self._loc = 'upper center'
else:
raise ValueError('Unknown location: {}'.format(location))
self.legend = ax.legend(
loc=self._loc, bbox_to_anchor=self._get_bbox_to_anchor(), **kwargs)
ax.figure.canvas.mpl_connect('resize_event', self.on_resize)
def on_resize(self, event):
self.legend.set_bbox_to_anchor(self._get_bbox_to_anchor())
def _get_bbox_to_anchor(self):
"""
Find the lengths in axes units that correspond to the specified
pixel_offset.
"""
screen_bbox = Bbox.from_bounds(
0, 0, self._pixel_offset, self._pixel_offset)
try:
ax_bbox = screen_bbox.inverse_transformed(ax.transAxes)
except np.linagl.LinAlgError:
ax_width = 0
ax_height = 0
else:
ax_width = ax_bbox.width
ax_height = ax_bbox.height
if self.location == 'right':
return (1 + ax_width, 0.5)
elif self.location == 'left':
return (-ax_width, 0.5)
elif self.location == 'upper':
return (0.5, 1 + ax_height)
elif self.location == 'lower':
return (0.5, -ax_height)
x = np.arange(5)
y = np.random.randn(5)
fig, ax = plt.subplots(tight_layout=True)
ax.plot(x, y, label='data1')
ax.plot(x, y-1, label='data2')
legend = FixedOutsideLegend(ax, 'lower', 20, ncol=2)
plt.show()
結果:
添加回答
舉報