【Matplotlib系列】绘制折线图时横轴太长,如何选中部分区域进行放大?不妨试试matplotlib的高级交互功能Span Selector

文章目录

  • 适用场合
  • 代码
  • 效果
  • 拓展
  • Reference

适用场合

折线图横轴太长的场合。或者举一个更具体的例子,如果绘制一只股票十年以来每天的收盘价,那么大概有2500条数据,横轴跨度很大,如果只想看一部分时段的数据,就可以用到Span Selector。用了这个功能你就不需要不停地选择数据,不停地plt.plot了。可以大大提高效率。

代码

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import SpanSelector


def onselect(xmin, xmax):
    indmin, indmax = np.searchsorted(x, (xmin, xmax))
    indmax = min(len(x) - 1, indmax)

    region_x = x[indmin:indmax]
    region_y = y[indmin:indmax]
    line2.set_data(region_x, region_y)
    ax2.set_xlim(region_x[0], region_x[-1])
    ax2.set_ylim(region_y.min(), region_y.max())
    fig.canvas.draw()


# Fixing random state for reproducibility
np.random.seed(19680801)

fig, (ax1, ax2) = plt.subplots(2, figsize=(8, 6))

x = np.arange(0.0, 5.0, 0.01)
y = np.sin(2*np.pi*x) + 0.5*np.random.randn(len(x))

ax1.plot(x, y)
ax1.set_ylim(-2, 2)
ax1.set_title('Press left mouse button and drag '
              'to select a region in the top graph')

line2, = ax2.plot([], [])

span = SpanSelector(ax1, onselect, 'horizontal', useblit=True,
                    rectprops=dict(alpha=0.5, facecolor='tab:blue'))
# Set useblit=True on most backends for enhanced performance.

plt.show()

效果

如下图所示,单击鼠标左键之后不放手拖动鼠标选择矩形区域如图中蓝色阴影部分,然后松开鼠标之后,选中的区域就会放大呈现到图中的第二个方框里。
【Matplotlib系列】绘制折线图时横轴太长,如何选中部分区域进行放大?不妨试试matplotlib的高级交互功能Span Selector_第1张图片

拓展

span selector这个交互功能很方便,也很强大。上边的例子只讲了绘制单条折线的情况,我自己额外实现了图中含有多条折线的情况,如果需要请在评论区留言。

Reference

  1. Matplotlib官方:Span Selector

你可能感兴趣的:(#,matplotlib,python,折线图,span,selector,matplotlib,数据可视化,可视化)