高级二维打印教程

Sage Document是为MAA预备研讨会“SAGE:在本科生中使用开源数学软件”开发的教程之一(由国家科学基金会提供,截止日期0817071)。它是在知识共享署名-Share Alike 3.0许可证下授权的 (CC BY-SA )。

由于Sage集成了以下项目 matplotlib ,Sage拥有全面的二维标绘能力。本工作表由以下各节组成:

本教程假定您熟悉Sage的基本知识,例如通过单击“评估”链接或通过按 Shift + Enter (按住 Shift 同时按下 Enter 键)。

绘图函数和曲线的绘制

笛卡尔图

简单的二次方是很容易的。

sage: plot(x^2, (x,-2,2))
Graphics object consisting of 1 graphics primitive

您可以通过添加“打印对象”来组合它们。

sage: regular = plot(x^2, (x,-2,2), color= 'purple')
sage: skinny = plot(4*x^2, (x,-2,2), color = 'green')
sage: regular + skinny
Graphics object consisting of 2 graphics primitives

Problem : Plot a green \(y=\sin(x)\) 与一张红色的 \(y=2\,\cos(x)\) 。(提示:您可以使用 pi 作为您的产品系列的一部分。)

除总尺寸外,还可以指定地块的边界。

sage: plot(1+e^(-x^2), xmin=-2, xmax=2, ymin=0, ymax=2.5, figsize=10)
Graphics object consisting of 1 graphics primitive

Problem : Plot \(y=5+3\,\sin(4x)\) 有合适的边界。

您可以添加大量额外信息。

sage: exponential = plot(1+e^(-x^2), xmin=-2, xmax=2, ymin=0, ymax=2.5)
sage: max_line = plot(2, xmin=-2, xmax=2, linestyle='-.', color = 'red')
sage: min_line = plot(1, xmin=-2, xmax=2, linestyle=':', color = 'red')
sage: exponential + max_line + min_line
Graphics object consisting of 3 graphics primitives

您可以用透明颜色填充区域,并加厚曲线。本例使用几个选项微调我们的图形。

sage: exponential = plot(1+e^(-x^2), xmin=-2, xmax=2, ymin=0, ymax=2.5, fill=0.5, fillcolor='grey', fillalpha=0.3)
sage: min_line = plot(1, xmin=-2, xmax=2, linestyle='-', thickness= 6, color = 'red')
sage: exponential + min_line
Graphics object consisting of 3 graphics primitives
sage: sum([plot(x^n,(x,0,1),color=rainbow(5)[n]) for n in [0..4]])
Graphics object consisting of 5 graphics primitives

Problem : Create a plot showing the cross-section area for the following solid of revolution problem: Consider the area bounded by \(y=x^2-3x+6\) 和这条线 \(y=4\) 。通过绕直线旋转此区域来查找创建的体积 \(y=1\)

参数图

参数图需要参数的两个函数的列表;在Sage中,我们使用 square 用于分隔列表的方括号。另请注意,我们必须声明 t 首先将其作为变量。由于图形略宽于高,因此我们使用 aspect_ratio 选项(此类选项称为 keywords )以确保轴与我们希望如何查看此对象是正确的。

sage: t = var('t')
sage: parametric_plot([cos(t) + 3 * cos(t/9), sin(t) - 3 * sin(t/9)], (t, 0, 18*pi), fill = True, aspect_ratio=1)
Graphics object consisting of 2 graphics primitives

Problem :这些参数方程将创建内摆线。

\[X(T)=17\cos(T)+3\cos(17t/3)\]
\[Y(T)=17\sin(T)-3\sin(17t/3)\]

将其创建为参数化图。

根据您指定的变量和坐标的数量,Sage会自动打印二维或三维打印以及曲线或曲面。

sage: t = var('t')
sage: parametric_plot((t^2,sin(t)), (t,0,pi))
Graphics object consisting of 1 graphics primitive
sage: parametric_plot((t^2,sin(t),cos(t)), (t,0,pi))
Graphics3d Object
sage: r = var('r')
sage: parametric_plot((t^2,sin(r*t),cos(r*t)), (t,0,pi),(r,-1,1))
Graphics3d Object

极地图

Sage也可以做极地情节。

sage: polar_plot(2 + 2*cos(x), (x, 0, 2*pi), color=hue(0.5), thickness=4)
Graphics object consisting of 1 graphics primitive

虽然它们不是必须的,但这些示例中的许多都试图演示诸如上色、填充和阴影之类的东西,让您对可能性有一个感觉。

可以在列表(方括号)中指定多条极轴曲线。请注意填充颜色的自动渐变着色。

sage: t = var('t')
sage: polar_plot([cos(4*t) + 1.5,  0.5 * cos(4*t) + 2.5], (t, 0, 2*pi),
....:            color='black', thickness=2, fill=True, fillcolor='orange')
Graphics object consisting of 4 graphics primitives

问题:为以下问题绘制一张图。找出圆内的区域 \(r=2\) ,但在心形外 \(2+2\cos(\theta)\)

互动演示

看到所有这些东西放在一个非常好的教学图表中可能会很有趣。尽管这是相当高级的,因此您可能想跳过代码,但它并不像您认为的那样困难。

sage: html('<h2>Sine and unit circle (by Jurgis Pralgauskis)</h2> inspired by <a href="http://www.youtube.com/watch?v=Ohp6Okk_tww&feature=related">this video</a>' )
sage: # http://doc.sagemath.org/html/en/reference/sage/plot/plot.html
sage: radius = 100 # scale for radius of "unit" circle
sage: graph_params = dict(xmin = -2*radius,    xmax = 360,
....:                    ymin = -(radius+30), ymax = radius+30,
....:                    aspect_ratio=1,
....:                    axes = False
....:                    )
sage: def sine_and_unit_circle( angle=30, instant_show = True, show_pi=True ):
....:     ccenter_x, ccenter_y = -radius, 0  # center of cirlce on real coords
....:     sine_x = angle # the big magic to sync both graphs :)
....:     current_y = circle_y = sine_y = radius * sin(angle*pi/180)
....:     circle_x = ccenter_x + radius * cos(angle*pi/180)
....:     graph = Graphics()
....:     # we'll put unit circle and sine function on the same graph
....:     # so there will be some coordinate mangling ;)
....:     # CIRCLE
....:     unit_circle = circle((ccenter_x, ccenter_y), radius, color="#ccc")
....:     # SINE
....:     x = var('x')
....:     sine = plot( radius * sin(x*pi/180) , (x, 0, 360), color="#ccc" )
....:     graph += unit_circle + sine
....:     # CIRCLE axis
....:     # x axis
....:     graph +=  arrow( [-2*radius, 0], [0, 0], color = "#666" )
....:     graph += text("$(1, 0)$",  [-16, 16],  color = "#666")
....:     # circle y axis
....:     graph +=  arrow( [ccenter_x,-radius], [ccenter_x, radius], color = "#666" )
....:     graph += text("$(0, 1)$",  [ccenter_x, radius+15],  color = "#666")
....:     # circle center
....:     graph += text("$(0, 0)$",  [ccenter_x, 0],  color = "#666")
....:     # SINE x axis
....:     graph +=  arrow( [0,0], [360, 0], color = "#000" )
....:     # let's set tics
....:     # or http://aghitza.org/posts/tweak_labels_and_ticks_in_2d_plots_using_matplotlib/
....:     # or wayt for https://github.com/sagemath/sage/issues/1431
....:     # ['$-\pi/3$', '$2\pi/3$', '$5\pi/3$']
....:     for x in range(0, 361, 30):
....:         graph += point( [x, 0] )
....:         angle_label = ".  $%3d^{\circ}$ " % x
....:         if show_pi: angle_label += " $(%s\pi) $"% x/180
....:         graph += text(angle_label,  [x, 0], rotation=-90,
....:         vertical_alignment='top', fontsize=8, color="#000" )
....:     # CURRENT VALUES
....:     # SINE -- y
....:     graph +=  arrow( [sine_x,0], [sine_x, sine_y], width=1, arrowsize=3)
....:     graph +=  arrow( [circle_x,0], [circle_x, circle_y], width=1, arrowsize=3)
....:     graph +=  line(([circle_x, current_y], [sine_x, current_y]), rgbcolor="#0F0", linestyle = "--", alpha=0.5)
....:     # LABEL on sine
....:     graph += text("$(%d^{\circ}, %3.2f)$"%(sine_x, float(current_y)/radius),  [sine_x+30, current_y],  color = "#0A0")
....:     # ANGLE -- x
....:     # on sine
....:     graph += arrow( [0,0], [sine_x, 0], width=1, arrowsize=1, color='red')
....:     # on circle
....:     graph += disk( (ccenter_x, ccenter_y), float(radius)/4, (0, angle*pi/180), color='red', fill=False, thickness=1)
....:     graph +=  arrow( [ccenter_x, ccenter_y], [circle_x, circle_y],
....:                  rgbcolor="#cccccc", width=1, arrowsize=1)
....:     if instant_show:
....:         show (graph,  **graph_params)
....:     return graph
sage: #####################
sage: # make Interaction
sage: ######################
sage: @interact
sage: def _( angle = slider([0..360], default=30, step_size=5,
....:          label="Pasirinkite kampą:    ", display_value=True) ):
....:     sine_and_unit_circle(angle, show_pi = False)

绘制数据

绘制数据点

有时,人们希望简单地绘制数据。在这里,我们演示了几种绘制点和数据的方法,这些方法简单地近似于

\[F_n=\frac{1}{\sqrt{5}}\left(\frac{1+\sqrt{5}}{2}\right)^n\; ,\]

这是相当不错的,在大约 \(n=5\)

首先,我们注意到斐波纳契数是内置的。

sage: fibonacci_sequence(6)
<generator object fibonacci_sequence at ...>
sage: list(fibonacci_sequence(6))
[0, 1, 1, 2, 3, 5]

这个 enumerate 命令对于获取列表并将其与计数数字进行协调非常有用。

sage: list(enumerate(fibonacci_sequence(6)))
[(0, 0), (1, 1), (2, 1), (3, 2), (4, 3), (5, 5)]

所以我们只定义了我们将要绘制的数字和坐标对。

sage: fibonacci = list(enumerate(fibonacci_sequence(6)))
sage: f(n)=(1/sqrt(5))*((1+sqrt(5))/2)^n
sage: asymptotic = [(i, f(i)) for i in range(6)]
sage: fibonacci
[(0, 0), (1, 1), (2, 1), (3, 2), (4, 3), (5, 5)]
sage: asymptotic
[(0, 1/5*sqrt(5)), (1, 1/10*sqrt(5)*(sqrt(5) + 1)), (2, 1/20*sqrt(5)*(sqrt(5) + 1)^2), (3, 1/40*sqrt(5)*(sqrt(5) + 1)^3), (4, 1/80*sqrt(5)*(sqrt(5) + 1)^4), (5, 1/160*sqrt(5)*(sqrt(5) + 1)^5)]

现在,我们不仅可以打印两组点,还可以使用文档中的几个选项来绘制点。那些来自其他系统的人可能更喜欢 list_plot

sage: fib_plot=list_plot(fibonacci, color='red', pointsize=30)
sage: asy_plot = list_plot(asymptotic, marker='D',color='black',thickness=2,plotjoined=True)
sage: show(fib_plot+asy_plot, aspect_ratio=1)

其他选项包括 linepoints ,以及 scatter_plot 。为不同的数据选择标记对于生成可发布的图形特别有帮助。

sage: fib_plot=scatter_plot(fibonacci, facecolor='red', marker='o',markersize=40)
sage: asy_plot = line(asymptotic, marker='D',color='black',thickness=2)
sage: show(fib_plot+asy_plot, aspect_ratio=1)

等高线类型曲线图

等高线图

在尝试处理多变量函数以及建模时,等值线绘制非常有用。基本语法本质上与3D绘图相同,只是2D绘图语法的扩展。

sage: f(x,y)=y^2+1-x^3-x
sage: contour_plot(f, (x,-pi,pi), (y,-pi,pi))
Graphics object consisting of 1 graphics primitive

我们可以更改颜色、指定等高线、标记曲线和许多其他事情。当有多个级别时, colorbar 关键字对于跟踪它们变得非常有用。请注意,与许多其他选项不同,它只能是 TrueFalse (对应于它是否出现)。

sage: contour_plot(f, (x,-pi,pi), (y,-pi,pi),colorbar=True,labels=True)
Graphics object consisting of 1 graphics primitive

这个例子很简单,但说明了格式化、标号和各种内置色阶(色彩映射表或 cmap )。看起来奇怪的结构对应于 label_fmt 是一种称为 dictionary ,并被证明对更高级的Sage用法很有用;它由由冒号连接的对组成,所有对都在花括号内。

sage: contour_plot(f, (x,-pi,pi), (y,-pi,pi), contours=[-4,0,4], fill=False,
....:     cmap='cool', labels=True, label_inline=True,
....:     label_fmt={-4:"low", 0:"medium", 4: "hi"}, label_colors='black')
Graphics object consisting of 1 graphics primitive

隐式绘制是一种特殊类型的等高线绘制(它们只绘制零等值线)。

sage: f(x,y)
-x^3 + y^2 - x + 1
sage: implicit_plot(f(x,y)==0,(x,-pi,pi),(y,-pi,pi))
Graphics object consisting of 1 graphics primitive

密度图类似于等高线图,但没有离散级别。

sage: density_plot(f, (x, -2, 2), (y, -2, 2))
Graphics object consisting of 1 graphics primitive

有时等值线图可能会有一些误导性(这使得 great 关于无知依赖技术的问题的课堂讨论)。在这里,我们结合了密度图和等高线图,以更好地显示函数正在发生的情况。

sage: density_plot(f,(x,-2,2),(y,-2,2))+contour_plot(f,(x,-2,2),(y,-2,2),fill=False,labels=True,label_inline=True,cmap='jet')
Graphics object consisting of 2 graphics primitives

熟悉不同情节的各种选择是值得的,特别是如果你要在给定的工作表或教学情况下做很多这样的事情。

以下是等高线绘制的选项。

  • 它们作为“属性”-没有括号- contour_plot 对象。

  • 它们是作为词典提供的(参见 the programming tutorial )。

sage: contour_plot.options
{'aspect_ratio': 1,
 'axes': False,
 'colorbar': False,
 'contours': None,
 'fill': True,
 'frame': True,
 'labels': False,
 'legend_label': None,
 'linestyles': None,
 'linewidths': None,
 'plot_points': 100,
 'region': None}

让我们更改它,这样所有未来的等高线图都不会有填充。这就是我们中的一些人可能在课堂上使用它们的方式。我们还将检查是否发生了更改。

sage: contour_plot.options["fill"]=False
sage: contour_plot.options
{'aspect_ratio': 1,
 'axes': False,
 'colorbar': False,
 'contours': None,
 'fill': False,
 'frame': True,
 'labels': False,
 'legend_label': None,
 'linestyles': None,
 'linewidths': None,
 'plot_points': 100,
 'region': None}

而且它起作用了!

sage: contour_plot(f,(x,-2,2),(y,-2,2))
Graphics object consisting of 1 graphics primitive

当然,我们可以随时访问默认选项来提醒我们。

sage: contour_plot.defaults()
{'aspect_ratio': 1,
 'axes': False,
 'colorbar': False,
 'contours': None,
 'fill': True,
 'frame': True,
 'labels': False,
 'legend_label': None,
 'linestyles': None,
 'linewidths': None,
 'plot_points': 100,
 'region': None}

矢量场

向量场的语法与其他多变量结构非常相似。请注意,在3D情况下,箭头已适当缩放,并按长度上色。

sage: var('x,y')
(x, y)
sage: plot_vector_field((-y+x,y*x),(x,-3,3),(y,-3,3))
Graphics object consisting of 1 graphics primitive
sage: var('x,y,z')
(x, y, z)
sage: plot_vector_field3d((-y,-z,x), (x,-3,3),(y,-3,3),(z,-3,3))
Graphics3d Object

理想情况下,使用3D眼镜查看3D矢量场曲线图(右击曲线图并选择“样式”和“立体图”)

复杂的地块

我们可以绘制复变量的函数,其中量值由亮度表示(黑色表示零量值),而自变量由色调表示(红色表示正实数)。

sage: f(z) = exp(z) #z^5 + z - 1 + 1/z
sage: complex_plot(f, (-5,5),(-5,5))
Graphics object consisting of 1 graphics primitive

区域图

这些图中的表达式为真,并且对于绘制不等式很有用。

sage: region_plot(cos(x^2+y^2) <= 0, (x, -3, 3), (y, -3, 3),aspect_ratio=1)
Graphics object consisting of 1 graphics primitive

我们也可以得到更花哨的选择。

sage: region_plot(sin(x)*sin(y) >= 1/4, (x,-10,10), (y,-10,10), incol='yellow', bordercol='black', borderstyle='dashed', plot_points=250,aspect_ratio=1)
Graphics object consisting of 2 graphics primitives

请记住,哪个命令可以提供有关语法、选项和示例的完整信息?

其他地块信息

内置图形对象

SAGE包括各种内置图形对象。它们对于将某些对象添加到一个人的绘图中特别有用,这些对象很难用等式描述,但仍然是基本的几何对象。在本节中,我们将尝试演示其中一些最有用的语法;对于大多数它们,上下文(记住,append ? )帮助将提供更多细节。

支点

要说明一点,一个坐标对就足够了。

sage: point((3,5))
Graphics object consisting of 1 graphics primitive

如何生成多个点并不重要;它们必须通过列表(方括号)作为输入进入。在这里,我们演示了实现这一点的艰难(但幼稚)和简单(但稍微复杂一些)的方法。

sage: f(x)=x^2
sage: points([(0,f(0)), (1,f(1)), (2,f(2)), (3,f(3)), (4,f(4))])
Graphics object consisting of 1 graphics primitive
sage: points([(x,f(x)) for x in range(5)])
Graphics object consisting of 1 graphics primitive

Sage会尝试自动判断您正在处理的维度有多少。

sage: f(x,y)=x^2-y^2
sage: points([(x,y,f(x,y)) for x in range(5) for y in range(5)])
Graphics3d Object

线条

线的语法与点的语法相同,但您可以得到...好吧,你也有连接线了!

sage: f(x)=x^2
sage: line([(x,f(x)) for x in range(5)])
Graphics object consisting of 1 graphics primitive

Sage有各种类型的磁盘和球体可供选择。通常情况下,只需要中心和半径,但也可以选择其他选项。

sage: circle((0,1),1,aspect_ratio=1)
Graphics object consisting of 1 graphics primitive
sage: disk((0,0), 1, (pi, 3*pi/2), color='yellow',aspect_ratio=1)
Graphics object consisting of 1 graphics primitive

也有椭圆和各种弧线;请参阅 full plot documentation

箭头

sage: arrow((0,0), (1,1))
Graphics object consisting of 1 graphics primitive

多边形

多边形将尝试完成自身并填充内部;否则语法是不言而喻的。

sage: polygon([[0,0],[1,1],[1,2]])
Graphics object consisting of 1 graphics primitive

文本

在2D中,您可以使用 text 指挥部。这可用于微调某些类型的标签。不幸的是,在3D中,文本只是文本。

sage: text(r'$\int_0^2 x^2\, dx$', (0.5,2))+plot(x^2,(x,0,2),fill=True)
Graphics object consisting of 3 graphics primitives

保存地块

我们可以将2D绘图保存为多种不同的格式。Sage可以根据图像的文件名确定格式。

sage: p=plot(x^2,(x,-1,1))
sage: p
Graphics object consisting of 1 graphics primitive

出于测试目的,我们使用Sage标准临时文件名;但是,您可以使用任何字符串作为您想要的名称,如 "my_plot.png"

sage: name = tmp_filename() # this is a string
sage: png_savename = name+'.png'
sage: p.save(png_savename)

在笔记本中,这些通常准备好通过细胞以小链接的方式下载。

sage: pdf_savename = name+'.pdf'
sage: p.save(pdf_savename)

值得注意的是,我们可以以准备好包含在网页中的格式进行输出。

sage: svg_savename = name+'.svg'
sage: p.save(svg_savename)