Thanks to visit codestin.com
Credit goes to github.com

Skip to content

[Sprint] Matlab fplot #1143

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Added ability to plot callables
Plotting functionality for Python callables, ala Matlab's 'fplot'
function.

A fixed step-size is used, but is recalculated to fit the viewport on
zooming and panning.  This has the effect of 'discovering' more of the function
when the user zooms in on the plot.

Only one callable is supported so far, it would be desirable to support
an array/list of callables and plot them all simultaneously.
  • Loading branch information
dmcdougall committed Jul 1, 2013
commit 0fd204902b0bd3c3f7ade93c6e512f77abf0fec2
1 change: 1 addition & 0 deletions boilerplate.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,7 @@ def boilerplate_gen():
'fill',
'fill_between',
'fill_betweenx',
'fplot',
'hexbin',
'hist',
'hist2d',
Expand Down
10 changes: 10 additions & 0 deletions examples/pylab_examples/fplot_demo.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import numpy as np
import matplotlib.pyplot as plt

# Set up figure
fig, ax = plt.subplots()

# Plot function
fp = ax.fplot(np.tan, [0, 2])
ax.set_xlim([1, 2])
plt.show()
5 changes: 5 additions & 0 deletions lib/matplotlib/axes/_axes.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
import matplotlib.contour as mcontour
import matplotlib.dates as _ # <-registers a date unit converter
from matplotlib import docstring
import matplotlib.fplot as mfplot
import matplotlib.image as mimage
import matplotlib.legend as mlegend
import matplotlib.lines as mlines
Expand Down Expand Up @@ -3762,6 +3763,10 @@ def streamplot(self, x, y, u, v, density=1, linewidth=None, color=None,
return stream_container
streamplot.__doc__ = mstream.streamplot.__doc__

def fplot(self, *args, **kwargs):
return mfplot.fplot(self, *args, **kwargs)
fplot.__doc__ = mfplot.fplot.__doc__

@docstring.dedent_interpd
def barbs(self, *args, **kw):
"""
Expand Down
78 changes: 78 additions & 0 deletions lib/matplotlib/fplot.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
"""
1D Callable function plotting.
"""

import numpy as np


__all__ = ['fplot']


class FPlot(object):
def __init__(self, axes, *args, **kwargs):
self._process_args(*args, **kwargs)

self.axes = axes
self.axes.set_autoscale_on(False)

self.n = kwargs.pop('res', 1000)

self.x = np.linspace(self.limits[0], self.limits[1], self.n)
self.f_vals = np.asarray([self.f(xi) for xi in self.x])

self.fline, = self.axes.plot(self.x, self.f_vals)
self._process_singularities()
self.axes.set_xlim([self.x[0], self.x[-1]])
mn, mx = np.nanmin(self.f_vals), np.nanmax(self.f_vals)
self.axes.set_ylim([mn, mx])

axes.callbacks.connect('xlim_changed', self._update)
axes.callbacks.connect('ylim_changed', self._update)

def _process_args(self, *args, **kwargs):
# TODO: Check f is callable. If not callable, support array of callables.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Seems reasonable. Would be nice to document the args clearly at this point (for devs rather than users).

# TODO: Support y limits?
self.f = args[0]
self.limits = args[1]

def _update(self, axes):
# bounds is (l, b, w, h)
bounds = axes.viewLim.bounds
self.x = np.linspace(bounds[0], bounds[0] + bounds[2], self.n)
self.f_vals = [self.f(xi) for xi in self.x]
self._process_singularities()
self.fline.set_data(self.x, self.f_vals)
self.axes.figure.canvas.draw_idle()

def _process_singularities(self):
# Note: d[i] == f_vals[i+1] - f_vals[i]
d = np.diff(self.f_vals)

# 80% is arbitrary. Perhaps more control could be offered here?
badness = np.where(d > 0.80 * self.axes.viewLim.bounds[3])[0]

# We don't draw the signularities
for b in badness:
self.f_vals[b] = np.nan
self.f_vals[b + 1] = np.nan


def fplot(ax, *args, **kwargs):
"""
Plots a callable function f.

Parameters
----------
f : Python callable, the function that is to be plotted.
limits : 2-element array or list of limits: [xmin, xmax]. The function f
is to to be plotted between xmin and xmax.

Returns
-------
lines : `matplotlib.collections.LineCollection`
Line collection with that describes the function *f* between xmin
and xmax. all streamlines as a series of line segments.
"""
if not ax._hold:
ax.cla()
return FPlot(ax, *args, **kwargs)
1 change: 1 addition & 0 deletions lib/matplotlib/pylab.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@
figure - create or change active figure
fill - make filled polygons
findobj - recursively find all objects matching some criteria
fplot - a method to plot callables
gca - return the current axes
gcf - return the current figure
gci - get the current image, or None
Expand Down
18 changes: 18 additions & 0 deletions lib/matplotlib/pyplot.py
Original file line number Diff line number Diff line change
Expand Up @@ -2779,6 +2779,24 @@ def fill_betweenx(y, x1, x2=0, where=None, hold=None, **kwargs):

return ret

# This function was autogenerated by boilerplate.py. Do not edit as
# changes will be lost
@_autogen_docstring(Axes.fplot)
def fplot(*args, **kwargs):
ax = gca()
# allow callers to override the hold state by passing hold=True|False
washold = ax.ishold()
hold = kwargs.pop('hold', None)
if hold is not None:
ax.hold(hold)
try:
ret = ax.fplot(*args, **kwargs)
draw_if_interactive()
finally:
ax.hold(washold)

return ret

# This function was autogenerated by boilerplate.py. Do not edit as
# changes will be lost
@_autogen_docstring(Axes.hexbin)
Expand Down