python-3.x - 使用绘图数据的微型版本作为 python 中的图例句柄

标签 python-3.x matplotlib legend

有没有什么办法可以把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()

enter image description here

关于python-3.x - 使用绘图数据的微型版本作为 python 中的图例句柄,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52335974/

相关文章:

python - python3 中的 Requests.get 不起作用。需要帮助才能从搜索查询的所有页面获取数据

python - 在Python中连接多列上的两个数据框

python - 是否可以使用字典中的数据绘制线条?

matplotlib - 关闭轴,保持刻度

r - 如何在 R 中添加自定义图例?

css - IE 在 Fieldset 中发出 min margin-top Legends

python - Scrapy 导入错误 : cannot import name 'HTTPClientFactory' from 'twisted.web.client' (unknown location)

python - 遇到 : json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

python - 在极坐标图中的点周围绘制平滑轮廓

R - 图例 : assign multiple colours to the same text