Created
September 3, 2012 08:59
-
-
Save pierre-haessig/3607993 to your computer and use it in GitHub Desktop.
Change the appearance of the plotted line depending on the amount of zoom.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Change the appearance of the plotted line depending on the amount of zoom. | |
Line properties changed include: line width, line color and marker type | |
Code derived from the clippedline example | |
http://matplotlib.sourceforge.net/examples/pylab_examples/clippedline.html | |
""" | |
import numpy as np | |
import matplotlib.pyplot as plt | |
from matplotlib.lines import Line2D | |
class ZoomAdaptiveLine(Line2D): | |
""" | |
Change the appearence of the line depending on the the axes view limits | |
(this example assumes x is sorted) | |
""" | |
def __init__(self, ax, *args, **kwargs): | |
Line2D.__init__(self, *args, **kwargs) | |
self.color_orig = self.get_color() | |
def draw(self, renderer): | |
'''overloaded `draw` method of Line2D''' | |
xlim = self.axes.get_xlim() | |
ind0, ind1 = np.searchsorted(self._x, xlim) | |
N = ind1-ind0 # number of currenly displayed points | |
if N<100: | |
self.set_marker('d') | |
self.set_color('g') | |
self.set_lw(1) | |
elif N<1000: | |
self.set_marker('+') | |
self.set_color('c') | |
self.set_lw(2) | |
else: | |
self.set_marker('') | |
self.set_color(self.color_orig) | |
self.set_lw(2) | |
Line2D.draw(self, renderer) | |
fig = plt.figure() | |
ax = fig.add_subplot(111) | |
# Generate some sine wave : | |
t = np.arange(0.0, 100.0, 0.01) | |
s = np.sin(2*np.pi*t) | |
# Create the derrived Line2D object: | |
line = ZoomAdaptiveLine(ax, t, s, color='b', ls='-', lw=1) | |
# Create the plot: | |
ax.add_line(line) | |
ax.set_xlim(10,30) | |
ax.set_ylim(-1.1,1.1) | |
ax.set_title('Zoom in to see the change of linestyle') | |
plt.show() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment