Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plotting two functions simultaneously with matplotlib

basically I want to graph two functions

g1 = x*cos(x*pi)
g2 = 1 - 0.6x^2

and then plot the intersection, I already have a module that takes inputs close to the two lines intersections, and then converges to those points (there's four of them)

but I want to graph these two functions and their intersections using matplotlib but have no clue how. I've only graphed basic functions. Any help is greatly appreciated

like image 994
MITjanitor Avatar asked May 03 '13 04:05

MITjanitor


People also ask

How do you plot multiple functions in one plot in Python?

In Matplotlib, we can draw multiple graphs in a single plot in two ways. One is by using subplot() function and other by superimposition of second graph on the first i.e, all graphs will appear on the same plot.


1 Answers

Assuming you can get as far as plotting one function, with x and g1 as numpy arrays,

pylab.plot(x,g1)

just call plot again (and again) to draw any number of separate curves:

pylab.plot(x,g2)

finally display or save to a file:

pylab.show()

To indicate a special point such as an intersection, just pass in scalars for x, y and ask for a marker such 'x' or 'o' or whatever else you like.

pylab.plot(x_intersect, y_intersect, 'x', color="#80C0FF")

Alternatively, I often mark a special place along x with a vertical segment by plotting a quick little two-point data set:

pylab.plot( [x_special, x_special], [0.5, 1.9], '-b' )

I may hardcode the y values to look good on a plot for my current project, but obviously this is not reusable for other projects. Note that plot() can take ordinary python lists; no need to convert to numpy arrays.

If you can't get as far as plotting one function (just g1) then you need a basic tutorial in matplot lib, which wouldn't make a good answer here but please go visit http://matplotlib.org/ and google "matplotlib tutorial" or "matplotlib introduction".

like image 140
DarenW Avatar answered Sep 21 '22 02:09

DarenW