matplotlib绘制鼠标的十字光标(自定义方式,官方实例)

本文介绍了如何使用matplotlib的Cursor类创建自定义交互式十字光标,包括基础实现、优化的blitting技术和捕捉数据点的实现。通过实例展示了如何提高绘制效率并实现精确数据定位。

matplotlibwidgets模块提供Cursor类用于支持十字光标的生成。另外官方还提供了自定义十字光标的实例。

widgets模块Cursor类源码

class Cursor(AxesWidget):
    """
    A crosshair cursor that spans the axes and moves with mouse cursor.

    For the cursor to remain responsive you must keep a reference to it.

    Parameters
    ----------
    ax : `matplotlib.axes.Axes`
        The `~.axes.Axes` to attach the cursor to.
    horizOn : bool, default: True
        Whether to draw the horizontal line.
    vertOn : bool, default: True
        Whether to draw the vertical line.
    useblit : bool, default: False
        Use blitting for faster drawing if supported by the backend.

    Other Parameters
    ----------------
    **lineprops
        `.Line2D` properties that control the appearance of the lines.
        See also `~.Axes.axhline`.

    Examples
    --------
    See :doc:`/gallery/widgets/cursor`.
    """

    def __init__(self, ax, horizOn=True, vertOn=True, useblit=False,
                 **lineprops):
        AxesWidget.__init__(self, ax)

        self.connect_event('motion_notify_event', self.onmove)
        self.connect_event('draw_event', self.clear)

        self.visible = True
        self.horizOn = horizOn
        self.vertOn = vertOn
        self.useblit = useblit and self.canvas.supports_blit

        if self.useblit:
            lineprops['animated'] = True
        self.lineh = ax.axhline(ax.get_ybound()[0], visible=False, **lineprops)
        self.linev = ax.axvline(ax.get_xbound()[0], visible=False, **lineprops)

        self.background = None
        self.needclear = False

    def clear(self, event):
        """Internal event handler to clear the cursor."""
        if self.ignore(event):
            return
        if self.useblit:
            self.background = self.canvas.copy_from_bbox(self.ax.bbox)
        self.linev.set_visible(False)
        self.lineh.set_visible(False)
        
    def onmove(self, event):
        """Internal event handler to draw the cursor when the mouse moves."""
        if self.ignore(event):
            return
        if not self.canvas.widgetlock.available(self):
            return
        if event.inaxes != self.ax:
            self.linev.set_visible(False)
            self.lineh.set_visible(False)

            if self.needclear:
                self.canvas.draw()
                self.needclear = False
            return
        self.needclear = Tr
使用matplotlib绘制折线图并自定义横坐标,可按以下步骤操作: ### 1. 导入必要的库 一般使用`matplotlib.pyplot`库来进行绘图,导入语句如下: ```python import matplotlib.pyplot as plt ``` ### 2. 准备数据 包括自定义的横坐标数据和对应的纵坐标数据。 ### 3. 绘制折线图 使用`plt.plot()`函数,传入自定义的横坐标数据和纵坐标数据。 ### 示例代码 以下是一个简单的示例,展示如何使用matplotlib绘制折线图并自定义横坐标: ```python from matplotlib import pyplot as plt # 自定义横坐标 x = ['A', 'B', 'C', 'D', 'E'] # 纵坐标数据 y = [10, 20, 15, 25, 30] # 绘制折线图 plt.plot(x, y) # 显示绘制的折线图 plt.show() ``` 在更复杂的实际应用中,可能还需要对图形进行更多的设置,如设置字体以显示中文、设置横坐标间距、竖向显示横坐标等。以下是一个更复杂的示例: ```python import matplotlib.pyplot as plt import xlrd import os import matplotlib.ticker as ticker # 设置字体以中文显示 plt.rcParams['font.sans-serif'] = ['SimHei'] # 定位到项目目录下 os.chdir('E:\\pycharm\\check') # 读取表格数据 data = xlrd.open_workbook('track.xls') table = data.sheets()[0] # 读取第一列和第6、7列的数据 cap1 = table.col_values(0)[1:] # 只取时间点 cap1_x = [x.split(" ")[1] for x in cap1] cap2 = table.col_values(5)[1:] cap3 = table.col_values(6)[1:] cap2_y = [round(x, 3) for x in cap2] cap3_y = [round(x, 3) for x in cap3] # 绘制折线图 fig, ax = plt.subplots(1, 1) plt.plot(cap1_x, cap2_y, color='r', label="ATT - RLSTM") plt.plot(cap1_x, cap3_y, color='g', label="CNN - RLSTM") plt.xlabel("温度差") plt.ylabel("时间点") # 图例右上角显示 plt.legend(loc="upper right") # 设置打印的密度 tick_spacing = 5 ax.xaxis.set_major_locator(ticker.MultipleLocator(tick_spacing)) # 设置显示字体的大小 plt.tick_params(axis='both', labelsize=14) # 对x轴进行翻转,竖向显示 plt.xticks(rotation=90, fontsize=14) # 显示图像 plt.show() ``` 此代码从Excel文件中读取数据自定义了横坐标,同时对图形进行了多方面的设置,如字体、横坐标间距、显示方向等[^3]。
评论 5
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值