Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to plot within user-defined function with python and matplotlib?

What I want to do is define a function which contain plotting sentences. Like this:

import matplotlib.pyplot as plt

def myfun(args, ax):
    #...do some calculation with args
    ax.plot(...)
    ax.axis(...)

fig.plt.figure()
ax1=fig.add_subplot(121)
ax2=fig.add_subplot(122)
para=[[args1,ax1],[args2,ax2]]
map(myfun, para)

I found that the myfun is called. If I add plt.show() in myfun, it can plot in the correct subplot, but nothing in the other one. And, if plt.show() is added in the end, nothing but two pairs of axis are plotted. I think the problem is that the figure is not transferred to the main function successfully. Is it possible to do something like this with python and matplotlib? Thanks!

like image 427
Fxyang Avatar asked Jun 17 '13 05:06

Fxyang


People also ask

Can matplotlib plot a function?

plot() Function. The plot() function in pyplot module of matplotlib library is used to make a 2D hexagonal binning plot of points x, y. Parameters: This method accept the following parameters that are described below: x, y: These parameter are the horizontal and vertical coordinates of the data points.

What is the use of matplotlib in Python explain use of plot () show () and title () functions of matplotlib?

matplotlib.pyplot is a collection of functions that make matplotlib work like MATLAB. Each pyplot function makes some change to a figure: e.g., creates a figure, creates a plotting area in a figure, plots some lines in a plotting area, decorates the plot with labels, etc.

Which function is used to plot the graph in matplotlib?

The matplotlib. pyplot. plot() function provides a unified interface for creating different types of plots. The simplest example uses the plot() function to plot values as x,y coordinates in a data plot.


1 Answers

Function that is called via map should have only one parameter.

import matplotlib.pyplot as plt

def myfun(args):
    data, ax = args
    ax.plot(*data)

fig = plt.figure()
ax1 = fig.add_subplot(121)
ax2 = fig.add_subplot(122)
para = [
    [[[1,2,3],[1,2,3]],ax1],
    [[[1,2,3],[3,2,1]],ax2],
]
map(myfun, para)
plt.show()

If you want to keep your function signature, use itertools.starmap.

import itertools
import matplotlib.pyplot as plt

def myfun(data, ax):
    ax.plot(*data)

fig = plt.figure()
ax1 = fig.add_subplot(121)
ax2 = fig.add_subplot(122)
para = [
    [[[1,2,3],[1,2,3]],ax1],
    [[[1,2,3],[3,2,1]],ax2],
]
list(itertools.starmap(myfun, para)) # list is need to iterator to be consumed.
plt.show()
like image 95
falsetru Avatar answered Oct 05 '22 05:10

falsetru