Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Avatar for KuCalc : devops.
Download
50640 views
1
# CoCalc Examples Documentation File for Plotting
2
# Copyright: Russ Hensel <[email protected]> and SageMath Inc., 2015
3
# License: Creative Commons: Attribution-ShareAlike 4.0 International (CC BY-SA 4.0)
4
5
language: sage
6
---
7
category: Plotting / 2D
8
---
9
title: Basic Plot
10
code: |
11
print "Basic plot: you need a variable, and a function of the variable here x*sin( x^2 )"
12
13
# this defaults many many things you can control
14
# here in 2 steps using plot() and show() (which can be combined into one line):
15
pt = plot( x*sin(x^2), x ) # create plot
16
show( pt )
17
descr: Basic plot of a function, letting most options default.
18
---
19
title: Upper and lower limit
20
code: |
21
print "Basic plot extended with upper lower, limit on x"
22
23
pt = plot( x*sin(x^2), x, 0, 6*pi ) # args in order: function, variable, lower limit, upper limit,
24
show( pt )
25
descr: >
26
Basic plot, but using plot arguments to control upper and lower
27
limits on x.
28
---
29
title: Many more options/arguments
30
code: |
31
print "Plot with many more options/arguments, used by name that are somewhat self explanatory -- tweak values to see what they do, or google them"
32
# show also offers named arguments for control.
33
34
pt = plot( x*sin(x^2), x, 0, 6*pi, rgbcolor="red", linestyle = "-", fill=False, thickness=1, legend_label ="a legend label" )
35
show( pt, aspect_ratio = 1, axes=true, frame=True, gridlines=false, figsize=4, xmin=-0, xmax=8*pi, ymin=-6, ymax=6 )
36
descr: >
37
Plot showing arguments to both plot and show that allow a lot of control over
38
various aspects of the graph.
39
---
40
title: Multiple lines/function
41
code: |
42
print "Plot Multiple lines/function on plots"
43
# also note that functions may be computed and put into variables outside of plot() or show()
44
45
function1 = x*sin(x^2)
46
47
function2 = x^.5*sin(x)
48
49
pt1 = plot( function1, x, 0, 6*pi, rgbcolor="red", linestyle = "-", fill=False, thickness=1, legend_label ="functionl" )
50
pt2 = plot( function2, x, 0, 6*pi, rgbcolor="blue", linestyle = "--", fill=False, thickness=1, legend_label ="function2" )
51
show( pt1 + pt2, aspect_ratio = 1, axes=true, frame=True, gridlines=false, figsize=6, xmin=-0, xmax=8*pi, ymin=-8, ymax=8 )
52
descr: >
53
Multiple plots can be plotted on the same graph, optionally using different
54
line styles.
55
---
56
title: Custom tickmarks on the axes
57
code: |
58
print "Plot with ticks, LaTeX formatting at specific locations"
59
60
fx = 1 * (x^2)+1
61
pt = plot( fx ,x, 0,5, ticks=[[0,1,e,pi,sqrt(20)], 5 ], tick_formatter="latex")
62
63
show( pt, figsize=[3,3] )
64
descr: >
65
Tickmarks on the axes can be controlled both in position, spacing,
66
special values, and using LaTeX for values such as pi.
67
---
68
title: Using Python functions
69
code: |
70
print "Plot using Python functions defined using 'def:'"
71
# see http://www.sagemath.org/doc/tutorial/tour_functions.html
72
73
def f(z): # this and next line define a Python function
74
return z^2
75
76
print "Define plot and show it in one line of code"
77
show( plot(f, 0, 2), figsize=[6,2] )
78
79
print "Alternate syntax "
80
var( "z" )
81
show( plot(f(z), z, 0, 2), figsize=[6,2], )
82
descr: >
83
Plot using Python functions.
84
Python functions are defined using the keyword def.
85
---
86
category: plotting / 2D Advanced
87
---
88
title: Implicit Plot
89
code: |
90
print "Implicit plot ( here function of x, y not solved for y )"
91
92
var ('x y')
93
imp = exp(x)==y^2
94
implicit_plot(imp, (x,-2,2), (y,-3,3), linestyle="--", figsize=4, axes="true", aspect_ratio=1)
95
descr: >
96
Implicit plots are used where the relationship is implicit in an equation
97
rather than explicitly solved.
98
---
99
title: Parametric Plot
100
code: |
101
print "Parametric Plot ( here 3 functions)"
102
# for graphing parametric equations ( 2 functions with a common variable implying a relation between the 2 functions )
103
# 3 plots all controlled by the parameter t
104
105
var( "t" ) # our parameter
106
107
ll = -1. * pi # lower limit of graph
108
ul = 1. * pi # upper limit of graph
109
110
# parametric_plot( x axis function, y axis function ) , ( parametric variable, min value, max value ), other plot args )
111
112
p1 = parametric_plot((cos(t),sin(t)), (t, ll, ul), rgbcolor=hue(0.2))
113
p2 = parametric_plot((cos(t),sin(t)^4), (t, ll, ul), rgbcolor=hue(0.4))
114
p3 = parametric_plot((cos(t),sin(t)^8), (t, ll, ul), rgbcolor=hue(0.6))
115
116
show( p1+p2+p3, axes=false)
117
descr: >
118
Parametric plots are used where the relationship between variables is implied by
119
their relationship to a third variable, the parameter.
120
---
121
title: Polar Plot
122
code: |
123
print "Polar Plot"
124
125
# Plot using polar coordinates: note that many of the options for plot() work here.
126
127
var( "theta" )
128
129
f = 1-2*sin(2*theta); show( f )
130
131
pp = polar_plot( f, theta, 0, 2*pi, rgbcolor="red", linestyle = "--" )
132
show( pp )
133
descr: >
134
Polar plots are used where the relationship between x and y, in Cartesian
135
coordinates, is expressed in terms of r an theta, in polar coordinates.
136
---
137
title: Slope Field
138
code: |
139
print "Plot Slope Field"
140
141
var( "x" )
142
var( "y" )
143
144
slope = y ^ 2 # define the slope to be the value of the function y^2
145
146
pt = plot_slope_field( slope, ( x, -1, 1 ), ( y, .001, 10 ), plot_points = 10 ) # plot_points: higher numbers plot more "slopes"
147
show( pt, aspect_ratio='automatic' ) # aspect_ratio: try .1, 1, 10 'automatic' or leave out and let it default
148
descr: >
149
Slope fields show the slope of 2 variables defined over a "field", that is
150
a relationship between x, an y that extends over an area of the plane ( 2 D).
151
The slope is indicated by the slope of a short line segment.
152
---
153
title: ODE Slope Field
154
descr: |
155
This example shows, how the solution of the differential equation
156
$$\frac{dy}{dx} + \frac{y}{x} + x = 2$$
157
with the initial conditions $y(2) = 4$
158
looks like.
159
code: |
160
x = var('x')
161
y = function('yy')(x)
162
eq = diff(y, x) == - y/x - x + 2
163
h = desolve(eq, y, [2, 4])
164
sol(x) = h.expand()
165
print "solution:", sol
166
167
# substituting the solution for y(x) in the right hand side
168
substituted = eq.rhs().substitute_function(yy, sol)
169
170
P1 = plot_slope_field( substituted, (x, 0, 6), (y, -5, 15), headlength = 4, headaxislength=3 )
171
P2 = plot( sol, (x, 0, 6), ymax=15, ymin=-5 )
172
P = P1 + P2
173
P.show()
174
---
175
title: Vector Field
176
code: |
177
print "Plot vector field"
178
179
var( "x" )
180
var( "y" )
181
182
A = x - sin(y)
183
B = -y * cos(x)
184
185
field = (A,B)
186
187
H = plot_vector_field( field, (x,0,2*pi), (y,0,2*pi), plot_points=15, color='green' ) # plot_points: higher numbers plot more vectors
188
show( H )
189
descr: >
190
Plot of a vector field shows an arrow of variable length indicating the
191
direction an magnitude of the vector at a large number of points over
192
the area of the graph.
193
---
194
title: List of points
195
code: |
196
print "Plot of a list of points"
197
198
# either type of list works
199
dictionary_list = {22: 3365, 27: 3295, 37: 3135, 42: 3020, 47: 2880, 52: 2735, 57: 2550}
200
tuple_list = [ ( 22, 3365) , ( 27, 3295 ), ( 37, 3135 ), ( 42, 3020 ), ( 47, 2880 ), ( 52, 2735 ), (57, 2550 ) ]
201
202
listPlot = list_plot( dictionary_list )
203
204
show( listPlot, xmin=0, xmax =50, ymin=2000, ymax=4000, figsize=[4,4] )
205
descr: >
206
Points, contained int Python lists, are all plotted.
207
The lists may be dictionary lists, or lists of 2D tuples.
208
---
209
title: Scatter Plot with Line
210
code: |
211
print "Scatter plot and line" # http://www.packtpub.com/article/plotting-data-sage
212
213
# python function
214
def noisy_line(m, b, x):
215
ret = m * x + b + 0.5 * (random() - 0.5)
216
return ret
217
218
slope = 1.0
219
intercept = -0.5
220
221
x_coords = [random() for t in range(50)]
222
y_coords = [noisy_line(slope, intercept, x) for x in x_coords]
223
224
sp = scatter_plot(zip(x_coords, y_coords))
225
226
sp += line([(0.0, intercept), (1.0, slope+intercept)], color='red')
227
228
sp.show( figsize=[6,2])
229
descr: >
230
Plot points, x coords in one list, y coords in another.
231
---
232
title: Contour Plot
233
code: |
234
print "Contour plot"
235
236
# this might be improved, some explanation
237
238
f = lambda x,y: cos(x*y)
239
show ( contour_plot(f, (-4, 4), (-4, 4)) )
240
descr: >
241
This plot indicates the contour of a function using
242
50 shades of gray.
243
---
244
category: plotting / Basic Elements
245
---
246
title: Points as points (plain and fancy)
247
code: |
248
print "Plotting points as points ( plain and fancy )"
249
250
plainPoints = point( [1, 1] ) + point( [2, 1] )
251
plot1 = plot( plainPoints )
252
253
show( plot1, figsize=4 )
254
255
fancyPoints = point((0.5, 0.5), rgbcolor=(1, 0, 0), size=30)
256
fancyPoints = fancyPoints + point((0.7, 0.7), rgbcolor=(0, 1, 0), size=50)
257
258
show( fancyPoints , figsize=4 )
259
descr: >
260
The graphic object point may be plotted using plot()
261
Plotting this way may combine various elements, both those
262
in this category but also other 2D plots.
263
---
264
title: Line with point at the end
265
code: |
266
print "Plot a line with point ( dot ) at end"
267
# computed in polar form, not required
268
269
r = 5
270
t = pi/4.
271
x = r*cos( t )
272
y = r*sin( t )
273
274
aPoint = point( ( x, y ), rgbcolor="red", size=30 )
275
aLine = line([(0.,0.), ( x, y ) ] , rgbcolor="blue" , linestyle = "dashed" )
276
277
plot = aPoint + aLine
278
show( plot, xmin=-1.2, xmax=5.2, ymin=-1.2, ymax=5.2 , figsize=[3,3] )
279
descr: >
280
A line is plotted with a point at the end.
281
---
282
title: Lines and points with Python function
283
code: |
284
Print "Plot lines and points with Python function"
285
286
def unitRotator( theta ):
287
x = cos( theta )
288
y = sin( theta )
289
aPoint = point2d( ( x, y ), rgbcolor="red", size=30 ) #point2d?
290
aLine = line([(0.,0.), ( x, y ) ] )
291
myRotator = aPoint +aLine
292
293
return myRotator
294
295
graphic = point( (0, 0 ) )
296
for theta in srange( .0, 2*pi, 2*pi/10):
297
graphic = graphic + unitRotator( theta )
298
299
show( graphic , xmin=-1.2, xmax=1.2, ymin=-1.2, ymax=1.2 , figsize=[3,3] )
300
descr: >
301
A Python function defines many lines and points all of which are plotted.
302
---
303
title: Arc
304
code: |
305
print "Plot an Arc"
306
307
graphic = ( arc((.1,.2), 1, sector=(0, 1*pi /4) ) )
308
309
show( graphic , xmin=-1.2, xmax=1.2, ymin=-1.2, ymax=1.2, figsize=[3,3] )
310
descr: >
311
Plot an a arc, a segment of a circle. Center, radius and section of
312
arc are all parameters.
313
---
314
title: Circle
315
code: |
316
print "Plot a Circle"
317
318
anGraphic = circle((0,0), .5, rgbcolor=(1,0,0), fill=False ) # fill controls filling of circle with color
319
320
show( anGraphic, aspect_ratio=1, figsize = 4 ,xmax = 1, ymax = 1)
321
descr: Plot a circle. Center, radius, color are parameters.
322
---
323
title: Arrow
324
code: |
325
print "Plot an Arrow"
326
327
anGraphic = arrow((0,1), (2,3) ) # start cord, end cord as tuples
328
329
show( anGraphic, figsize = 2 )
330
descr: Plot an Arrow, describe by starting and ending coordinates.
331
---
332
title: Text
333
code: |
334
print "Plot Text"
335
# text is followed by tuple for position
336
aGraphic = text("Sample Text", (5,4), rgbcolor=(1,0,0))
337
show( aGraphic, aspect_ratio=1, figsize = 3 )
338
descr: >
339
Plot Text, arguments for text, position, and color.
340
341