有没有什么办法可以把matplotlib中的图中绘制的线作为图例中的句柄?例如,我在考虑在这个基本代码中而不是图例中的直线有一个我绘制为 handle 的正弦波的小版本。
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0,15,0.1)
y = [np.sin(x1) for x1 in x]
plt.plot(x,y, label = 'sine wave')
plt.legend()
plt.show()
提前致谢!
最佳答案
@DizietAsahi 的回答给出了简单示例的正确结果,但对于其他 x 值会失败。因此,人们可能更普遍地使用转换后的 bbox,这样就不需要关心数据的实际值。
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.legend_handler import HandlerLine2D
import matplotlib.path as mpath
from matplotlib.transforms import BboxTransformFrom, BboxTransformTo, Bbox
class HandlerMiniatureLine(HandlerLine2D):
def create_artists(self, legend, orig_handle,
xdescent, ydescent, width, height, fontsize,
trans):
legline, _ = HandlerLine2D.create_artists(self,legend, orig_handle,
xdescent, ydescent, width, height, fontsize, trans)
legline.set_data(*orig_handle.get_data())
ext = mpath.get_paths_extents([orig_handle.get_path()])
if ext.width == 0:
ext.x0 -= 0.1
ext.x1 += 0.1
bbox0 = BboxTransformFrom(ext)
bbox1 = BboxTransformTo(Bbox.from_bounds(xdescent, ydescent, width, height))
legline.set_transform(bbox0 + bbox1 + trans)
return legline,
fig, ax = plt.subplots()
x = np.arange(0,15,0.1)
y = np.sin(x)
plt.plot(x-900,y+1500, label='sine wave')
plt.legend(handler_map={plt.Line2D: HandlerMiniatureLine()})
plt.show()
关于python-3.x - 使用绘图数据的微型版本作为 python 中的图例句柄,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52335974/