# Plot the level sets of a function

I'm trying to draw level set of a function f:R^2->R, that is the set of solutions of f(x,y)=h for a given h.

For that purpose I wrote the following

#! /usr/bin/sage -python
# -*- coding: utf8 -*-

from sage.all import *

def level_curve(f,h):
solutions_list = solve(f==h,y)
return [sol.rhs() for sol in solutions_list]

var('x,y')
f=x+y+2
for g in level_curve(f,3):
print g

print "-----"

f=x**2+y**2
for g in level_curve(f,3):
print g


This works, but I'm not satisfied principally because I got the level sets under the form of a list of functions. Moreover it will not work if the level set is vertical.

Thus I would prefer to get the solution under the form of a parametric curve.

Does Sage provides something for that ?

edit retag close merge delete

Sort by » oldest newest most voted

I'm not quite sure what you're looking for. If you want to plot the level sets, you have several options,which I've blatantly stolen from the level set examples worksheet by evanmb:

import matplotlib

var("x, y")
f = x+y+2

# manually using implicit plot for particular h values:
p = Graphics()
for h in [-5..5]:
p += implicit_plot(f==h,(x,-4,4),(y,-4,4))

p.show()

# using a full contour plot
contour_plot(f,(x,-4,4),(y,-4,4), fill=false, labels=true, contours=10, colorbar=true,cmap=matplotlib.cm.gist_rainbow).show(aspect_ratio=1)

# maybe filled
contour_plot(f,(x,-4,4),(y,-4,4), fill=True, labels=true, contours=10, label_colors='black',colorbar=true,cmap=matplotlib.cm.gist_rainbow).show(aspect_ratio=1)

# or 3d
plot3d(f,(x,-4,4),(y,-4,4))


Or is there something more analytic that you're trying to do first? Depending on how complicated your real functions will be, finding a parametric solution might be a challenge.

more

The aim being to show graphics to my students, a graphical solution is sufficient.

Obviously the advantage of an analytic solution is that it can be passed to pstricks and then be included in LaTeX figures in a smoother way than \includegraphics{blabla.png}.

BTW I found \psplotImp

more

You might look at SageTex for a very easy way to include plots and other Sage output in TeX. Basically, you can simply do something like \sageplot{contour_plot(f,(x,-4,4),(y,-4,4)} inside your tex document and the plot shows up in the pdf.

( 2011-02-08 18:20:18 -0500 )edit