Ticket #5448: trac-5448-matplotlib-axes-gridlines.4.patch
File trac-5448-matplotlib-axes-gridlines.4.patch, 54.4 KB (added by , 11 years ago) |
---|
-
sage/plot/axes.py
# HG changeset patch # User Jason Grout <jason-sage@creativetrax.com> # Date 1250665286 18000 # Node ID 91a0bec4200aa363bc94db1afbef9b4cae76223d # Parent 22919ed0d91f090084eceba9c37c832e920e7e89 [mq]: new-matplotlib.patch diff -r 22919ed0d91f -r 91a0bec4200a sage/plot/axes.py
a b 1 1 r""" 2 2 2D Axes 3 3 4 This module is deprecated and will be removed from a future version of 5 Sage. The axes and gridline functionality is now taken care of by 6 matplotlib constructs. 7 4 8 Sage provides several different axes for its 2D plotting functionality. 5 9 The 'look' of the axes are similar to what Mathematica provides for its 6 10 2D plotting. … … 29 33 import sage.misc.misc 30 34 from copy import copy 31 35 36 from sage.misc.misc import deprecation 37 deprecation('The axes module is deprecated; Sage now uses matplotlib constructs for the axes and gridlines. This module will be removed from a future version of Sage.') 38 39 32 40 class Axes(SageObject): 33 41 """ 34 42 Axes for Sage 2-D Graphics. … … 40 48 add_xy_matrix_frame_axes 41 49 42 50 """ 51 43 52 def __init__(self, color=(0,0,0), fontsize=8, linewidth=0.6,axes_labels=None, 44 53 axes_label_color=(0,0,0), tick_label_color=(0,0,0)): 54 deprecation('The axes module is deprecated; Sage now uses matplotlib constructs for the axes and gridlines. This module will be removed from a future version of Sage.') 45 55 self.__color = color 46 56 self.__tick_label_color = tick_label_color 47 57 self.__axes_labels = axes_labels … … 63 73 64 74 sage: from sage.plot.axes import Axes 65 75 sage: A = Axes() 76 doctest:...: DeprecationWarning: The axes module is deprecated; Sage now uses matplotlib constructs for the axes and gridlines. This module will be removed from a future version of Sage. 66 77 sage: A._tasteful_ticks(2^(-20*10),2^(-20*1)) 67 78 ([1.9999999999999999e-07, 3.9999999999999998e-07, 5.9999999999999997e-07, 7.9999999999999996e-07], 1.9999999999999999e-07, 1.9999999999999999e-07) 68 79 """ … … 506 517 TESTS: 507 518 sage: from sage.plot.axes import Axes 508 519 sage: Axes()._adjustments_for_frame(-10,40,10,35) 520 doctest:...: DeprecationWarning: The axes module is deprecated; Sage now uses matplotlib constructs for the axes and gridlines. This module will be removed from a future version of Sage. 509 521 (-11.0, 41.0, 9.5, 35.5) 510 522 """ 511 523 xmin = float(xmin); xmax=float(xmax); ymin=float(ymin); ymax=float(ymax) … … 645 657 646 658 TESTS: 647 659 sage: from sage.plot.axes import GridLines 660 doctest:...: DeprecationWarning: The axes module is deprecated; Sage now uses matplotlib constructs for the axes and gridlines. This module will be removed from a future version of Sage. 648 661 sage: GridLines() 649 662 <class 'sage.plot.axes.GridLines'> 650 663 sage: gl = GridLines(False) … … 658 671 sage: gl = GridLines([range(-10,10,2), lambda x,y:srange(x,y,0.5)]) 659 672 sage: gl = GridLines(None, dict(color="red"), 660 673 ... dict(linestyle=":"), dict(color="blue")) 674 doctest:...: DeprecationWarning: The axes module is deprecated; Sage now uses matplotlib constructs for the axes and gridlines. This module will be removed from a future version of Sage. 661 675 sage: gl = GridLines(None, dict(rgbcolor="red"), 662 676 ... dict(linestyle=":"), dict(color="blue")) 663 677 """ 678 deprecation('The axes module is deprecated; Sage now uses matplotlib constructs for the axes and gridlines. This module will be removed from a future version of Sage.') 664 679 self.__gridlines = gridlines 665 680 666 681 defaultstyle = dict(color=(0.3,0.3,0.3),linewidth=0.4) … … 698 713 699 714 sage: subplot = Figure().add_subplot(111) 700 715 sage: GridLines().add_gridlines(subplot,*lims) 716 doctest:...: DeprecationWarning: The axes module is deprecated; Sage now uses matplotlib constructs for the axes and gridlines. This module will be removed from a future version of Sage. 701 717 sage: len(subplot.lines) 702 718 0 703 719 … … 708 724 709 725 sage: subplot = Figure().add_subplot(111) 710 726 sage: GridLines(True).add_gridlines(subplot,*lims) 727 doctest:...: DeprecationWarning: The axes module is deprecated; Sage now uses matplotlib constructs for the axes and gridlines. This module will be removed from a future version of Sage. 711 728 sage: len(subplot.lines) 712 729 13 713 730 … … 750 767 sage: GridLines("automatic", dict(color="red"), 751 768 ... dict(linestyle=":"), 752 769 ... dict(color="blue")).add_gridlines(subplot,*lims) 770 doctest:...: DeprecationWarning: The axes module is deprecated; Sage now uses matplotlib constructs for the axes and gridlines. This module will be removed from a future version of Sage. 753 771 sage: len(subplot.lines) 754 772 13 755 773 … … 856 874 TESTS: 857 875 sage: from sage.plot.axes import GridLines 858 876 sage: GridLines()._get_ticks_locations([-10,20]) 877 doctest:...: DeprecationWarning: The axes module is deprecated; Sage now uses matplotlib constructs for the axes and gridlines. This module will be removed from a future version of Sage. 859 878 [-10, -5, 0, 5, 10, 15, 20] 860 879 sage: GridLines()._get_ticks_locations([10,35],"minor") 861 880 [10.0, 11.0, 12.0, 13.0, ..., 32.0, 33.0, 34.0, 35.0] … … 884 903 TESTS: 885 904 sage: from sage.plot.axes import GridLines 886 905 sage: GridLines()._get_adjustments_for_frame([-10,40],[10,35]) 906 doctest:...: DeprecationWarning: The axes module is deprecated; Sage now uses matplotlib constructs for the axes and gridlines. This module will be removed from a future version of Sage. 887 907 (-11.0, 41.0, 9.5, 35.5) 888 908 """ 889 909 return Axes()._adjustments_for_frame(*(xinterval+yinterval)) -
sage/plot/bar_chart.py
diff -r 22919ed0d91f -r 91a0bec4200a sage/plot/bar_chart.py
a b 108 108 datalist = numpy.array(self.datalist, dtype=float) 109 109 subplot.bar(ind, datalist, color=color, width=width) 110 110 111 @rename_keyword(color='rgbcolor') 111 112 @options(width=0.5, rgbcolor=(0,0,1)) 112 113 def bar_chart(datalist, **options): 113 114 """ -
sage/plot/bezier_path.py
diff -r 22919ed0d91f -r 91a0bec4200a sage/plot/bezier_path.py
a b 173 173 'ymin': self.vertices[:,1].min(), 174 174 'ymax': self.vertices[:,1].max()} 175 175 176 @rename_keyword(color='rgbcolor') 176 177 @options(alpha=1, fill=False, thickness=1, rgbcolor=(0,0,0), zorder=2, linestyle='solid') 177 178 def bezier_path(path, **options): 178 179 """ -
sage/plot/circle.py
diff -r 22919ed0d91f -r 91a0bec4200a sage/plot/circle.py
a b 205 205 from line import Line 206 206 return Line(xdata, ydata, options).plot3d().translate((0,0,z)) 207 207 208 208 @rename_keyword(color='rgbcolor') 209 209 @options(alpha=1, fill=False, thickness=1, edgecolor='black', facecolor='red', linestyle='solid', zorder=5) 210 210 def circle(center, radius, **options): 211 211 """ -
sage/plot/contour_plot.py
diff -r 22919ed0d91f -r 91a0bec4200a sage/plot/contour_plot.py
a b 161 161 else: 162 162 subplot.contour(self.xy_data_array, contours, cmap=cmap, extent=(x0,x1,y0,y1)) 163 163 164 @options(plot_points=25, fill=True, cmap='gray', contours=None )164 @options(plot_points=25, fill=True, cmap='gray', contours=None,frame=True) 165 165 def contour_plot(f, xrange, yrange, **options): 166 166 r""" 167 167 ``contour_plot`` takes a function of two variables, `f(x,y)` -
sage/plot/line.py
diff -r 22919ed0d91f -r 91a0bec4200a sage/plot/line.py
a b 243 243 return line3d(points, **kwds) 244 244 245 245 246 @rename_keyword(color='rgbcolor') 246 247 @options(alpha=1, rgbcolor=(0,0,1), thickness=1) 247 248 def line2d(points, **options): 248 249 r""" -
sage/plot/matrix_plot.py
diff -r 22919ed0d91f -r 91a0bec4200a sage/plot/matrix_plot.py
a b 156 156 subplot.imshow(self.xy_data_array, cmap=cmap, interpolation='nearest', extent=(0,self.xrange[1],0,self.yrange[1])) 157 157 158 158 159 @options(cmap='gray',marker='.' )159 @options(cmap='gray',marker='.',frame=True) 160 160 def matrix_plot(mat, **options): 161 161 r""" 162 162 A plot of a given matrix or 2D array. -
sage/plot/plot.py
diff -r 22919ed0d91f -r 91a0bec4200a sage/plot/plot.py
a b 72 72 73 73 EXAMPLES: We construct a plot involving several graphics objects:: 74 74 75 sage: G = plot(cos, -5, 5, thickness=5, rgbcolor=(0.5,1,0.5))76 sage: P = polygon([[1,2], [5,6], [5,0]], rgbcolor=(1,0,0))75 sage: G = plot(cos, -5, 5, thickness=5, color='green') 76 sage: P = polygon([[1,2], [5,6], [5,0]], color='red') 77 77 sage: G + P # show it 78 78 79 79 We draw a circle and a curve:: 80 80 81 sage: circle((1,1), 1) + plot(x^2, ( 0,5))81 sage: circle((1,1), 1) + plot(x^2, (x,0,5)) 82 82 83 83 Notice that the above circle is not round, because the aspect ratio 84 84 of the coordinate system is not 1:1. The 85 85 ``aspect_ratio`` option to show allows us to fix 86 86 this:: 87 87 88 sage: show(circle((1,1), 1) + plot(x^2, ( 0,5)), aspect_ratio=1)88 sage: show(circle((1,1), 1) + plot(x^2, (x,0,5)), aspect_ratio=1) 89 89 90 90 With an aspect ratio of 2 the circle is squashed half way down (it 91 91 looks twice as wide as it does tall):: 92 92 93 sage: show(circle((1,1), 1) + plot(x^2, ( 0,5)), aspect_ratio=2)93 sage: show(circle((1,1), 1) + plot(x^2, (x,0,5)), aspect_ratio=2) 94 94 95 95 Use figsize to set the actual aspect ratio of the rendered image 96 96 (i.e., of the frame). For example, this image is twice as many 97 97 pixels wide as it is tall:: 98 98 99 sage: show(circle((1,1), 1) + plot(x^2, ( 0,5)), figsize=[8,4])99 sage: show(circle((1,1), 1) + plot(x^2, (x,0,5)), figsize=[8,4]) 100 100 101 101 Next we construct the reflection of the above polygon about the 102 102 `y`-axis by iterating over the list of first-coordinates of … … 104 104 Polygon; note that `P` is a Graphics object, which consists 105 105 of a single polygon):: 106 106 107 sage: Q = polygon([(-x,y) for x,y in P[0]], rgbcolor=(0,0,1))107 sage: Q = polygon([(-x,y) for x,y in P[0]], color='blue') 108 108 sage: Q # show it 109 109 110 110 We combine together different graphics objects using "+":: … … 135 135 136 136 sage: i = CDF.0 # define i this way for maximum speed. 137 137 sage: p1 = plot(lambda t: arg(zeta(0.5+t*i)), 1,27,rgbcolor=(0.8,0,0)) 138 sage: p2 = plot(lambda t: abs(zeta(0.5+t*i)), 1,27, rgbcolor=hue(0.7))138 sage: p2 = plot(lambda t: abs(zeta(0.5+t*i)), 1,27,color=hue(0.7)) 139 139 sage: print p1 + p2 140 140 Graphics object consisting of 2 graphics primitives 141 141 sage: p1 + p2 # display it … … 149 149 sage: g = Graphics() 150 150 sage: for i in range(60): 151 151 ... p = polygon([(i*cos(i),i*sin(i)), (0,i), (i,0)],\ 152 ... rgbcolor=hue(i/40+0.4), alpha=0.2)152 ... color=hue(i/40+0.4), alpha=0.2) 153 153 ... g = g + p 154 154 ... 155 155 sage: g.show(dpi=200, axes=False) … … 157 157 Another graph:: 158 158 159 159 sage: x = var('x') 160 sage: P = plot(sin(x)/x, -4,4, rgbcolor=(0,0,1)) + \161 ... plot(x*cos(x), -4,4, rgbcolor=(1,0,0)) + \162 ... plot(tan(x),-4,4, rgbcolor=(0,1,0))160 sage: P = plot(sin(x)/x, -4,4, color='blue') + \ 161 ... plot(x*cos(x), -4,4, color='red') + \ 162 ... plot(tan(x),-4,4, color='green') 163 163 ... 164 164 sage: P.show(ymin=-pi,ymax=pi) 165 165 … … 191 191 An illustration of integration:: 192 192 193 193 sage: f(x) = (x-3)*(x-5)*(x-7)+40 194 sage: P = line([(2,0),(2,f(2))], rgbcolor=(0,0,0))195 sage: P += line([(8,0),(8,f(8))], rgbcolor=(0,0,0))194 sage: P = line([(2,0),(2,f(2))], color='black') 195 sage: P += line([(8,0),(8,f(8))], color='black') 196 196 sage: P += polygon([(2,0),(2,f(2))] + [(x, f(x)) for x in [2,2.1,..,8]] + [(8,0),(2,0)], rgbcolor=(0.8,0.8,0.8)) 197 sage: P += text("$\\int_{a}^b f(x) dx$", (5, 20), fontsize=16, rgbcolor=(0,0,0))198 sage: P += plot(f, 1, 8.5, thickness=3)197 sage: P += text("$\\int_{a}^b f(x) dx$", (5, 20), fontsize=16, color='black') 198 sage: P += plot(f, (1, 8.5), thickness=3) 199 199 sage: P # show the result 200 200 201 202 201 203 NUMERICAL PLOTTING: 202 204 203 Sage also provides 2D plotting with an interface that is a likely 204 very familiar to people doing numerical computation. For example, 205 Sage includes Matplotlib, which provides 2D plotting with an interface 206 that is a likely very familiar to people doing numerical 207 computation. For example, 205 208 206 209 :: 207 210 … … 259 262 - William Stein (2008-01-19): raised the documentation coverage from a 260 263 miserable 12 percent to a 'wopping' 35 percent, and fixed and 261 264 clarified numerous small issues. 265 266 - Jason Grout (2009-09-05): shifted axes and grid functionality over 267 to matplotlib; fixed a number of smaller issues. 268 262 269 """ 263 270 264 271 ############################################################################ … … 348 355 # Sage startup times are much improved.) - William 349 356 ############### 350 357 351 #Sage 2D Graphics Axes class:352 from axes import Axes353 from axes import GridLines354 355 358 def is_Graphics(x): 356 359 """ 357 360 Return True if `x` is a Graphics object. … … 376 379 377 380 sage: G = Graphics(); print G 378 381 Graphics object consisting of 0 graphics primitives 379 sage: c = circle((1,1), 1 )382 sage: c = circle((1,1), 1,aspect_ratio=1) 380 383 sage: G+=c; print G 381 384 Graphics object consisting of 1 graphics primitive 382 385 383 386 Here we make a graphic of embedded isosceles triangles, coloring 384 387 each one with a different color as we go:: 385 388 386 sage: h=10; c=0.4; p=0. 1;389 sage: h=10; c=0.4; p=0.5; 387 390 sage: G = Graphics() 388 391 sage: for x in srange(1,h+1): 389 392 ... l = [[0,x*sqrt(3)],[-x/2,-x*sqrt(3)/2],[x/2,-x*sqrt(3)/2],[0,x*sqrt(3)]] 390 ... G+=line(l, rgbcolor=hue(c + p*(x/h)))393 ... G+=line(l,color=hue(c + p*(x/h))) 391 394 sage: G.show(figsize=[5,5]) 392 395 """ 393 396 … … 683 686 :: 684 687 685 688 sage: p = plot(sin(x), (x, 0, 10)) 686 sage: p.axes_labels([' x','y'])689 sage: p.axes_labels(['$x$','$y$']) 687 690 sage: p.axes_labels() 688 (' x', 'y')691 ('$x$', '$y$') 689 692 690 693 Now when you plot p, you see x and y axes labels:: 691 694 … … 1033 1036 EXAMPLES:: 1034 1037 1035 1038 sage: g1 = plot(abs(sqrt(x^3-1)), (x,1,5), frame=True) 1036 sage: g2 = plot(-abs(sqrt(x^3-1)), (x,1,5), rgbcolor=(1,0,0))1039 sage: g2 = plot(-abs(sqrt(x^3-1)), (x,1,5), color='red') 1037 1040 sage: g1 + g2 # displays the plot 1038 1041 1039 1042 TESTS:: … … 1149 1152 dpi=DEFAULT_DPI, axes=None, axes_labels=None,frame=False, 1150 1153 fontsize=None, aspect_ratio=None, 1151 1154 gridlines=None, gridlinesstyle=None, 1152 vgridlinesstyle=None, hgridlinesstyle=None) 1155 vgridlinesstyle=None, hgridlinesstyle=None,transparent=False, 1156 axes_pad=.02) 1153 1157 1154 1158 def show(self, **kwds): 1155 1159 """ … … 1184 1188 1185 1189 - ``gridlines`` - (default: None) can be any of the following: 1186 1190 1187 - 1191 - None, False: do not add grid lines. 1188 1192 1189 1193 - True, "automatic", "major": add grid lines at major ticks of the axes. 1190 1194 … … 1216 1220 - ``linkmode`` - (default: False) If True a string containing a link 1217 1221 to the produced file is returned. 1218 1222 1223 - ``transparent`` - (default: False) If True, make the background transparent. 1224 1225 - ``axes_pad`` - (default: 0.02) The percentage of the axis 1226 range that is added to each end of each axis. This helps 1227 avoid problems like clipping lines because of line-width, 1228 etc. To get axes that are exactly the specified limits, set 1229 ``axes_pad`` to zero. 1230 1219 1231 EXAMPLES:: 1220 1232 1221 sage: c = circle((1,1), 1, rgbcolor=(1,0,0))1233 sage: c = circle((1,1), 1, color='red') 1222 1234 sage: c.show(xmin=-1, xmax=3, ymin=-1, ymax=3) 1223 1235 1224 To correct the aspect ratio of certain graphics, it is necessary to1225 s how with a '``figsize``' of square dimensions.1236 To correct the aspect ratio of certain graphics, you can 1237 set the ``aspect_ratio`` to 1 1226 1238 1227 1239 :: 1228 1240 1229 sage: c.show(figsize=[5,5], xmin=-1, xmax=3, ymin=-1, ymax=3) 1241 sage: c.show(aspect_ratio=1, xmin=-1, xmax=3, ymin=-1, ymax=3) 1242 1243 You could also just make the dimensions of the picture square 1244 using ``figsize`` 1245 1246 :: 1247 1248 sage: c.show(figsize=[5,5], xmin=-1, xmax=3, ymin=-1, ymax=3) 1230 1249 1231 1250 You can turn off the drawing of the axes:: 1232 1251 1233 1252 sage: show(plot(sin,-4,4), axes=False) 1234 1253 1235 You can also label the axes:: 1254 You can also label the axes. Putting something in dollar 1255 signs formats it as a mathematical expression:: 1236 1256 1237 sage: show(plot(sin,-4,4), axes_labels=(' x','y'))1257 sage: show(plot(sin,-4,4), axes_labels=('$x$','$y$')) 1238 1258 1239 1259 You can turn on the drawing of a frame around the plots:: 1240 1260 1241 1261 sage: show(plot(sin,-4,4), frame=True) 1242 1262 1243 Add grid lines at the major ticks of the axes. 1263 You can make the background transparent:: 1264 1265 sage: plot(sin(x), (x, -4, 4), transparent=True) 1266 1267 Add grid lines at the major ticks of the axes. 1244 1268 1245 1269 :: 1246 1270 … … 1281 1305 1282 1306 sage: def maple_leaf(t): 1283 1307 ... return (100/(100+(t-pi/2)^8))*(2-sin(7*t)-cos(30*t)/2) 1284 sage: p = polar_plot(maple_leaf, -pi/4, 3*pi/2, rgbcolor="red",plot_points=1000) #long1308 sage: p = polar_plot(maple_leaf, -pi/4, 3*pi/2, color="red",plot_points=1000) #long 1285 1309 sage: p.show(gridlines=( [-3,-2.75,..,3], xrange(-1,5,2) )) #long 1286 1310 1287 1311 Add grid lines at specific positions (using functions). … … 1297 1321 1298 1322 :: 1299 1323 1300 sage: b = bar_chart([-3,5,-6,11], rgbcolor=(1,0,0))1324 sage: b = bar_chart([-3,5,-6,11], color='red') 1301 1325 sage: b.show(gridlines=([-1,-0.5,..,4],True), \ 1302 1326 ... gridlinesstyle=dict(color="blue", linestyle=":")) 1303 1327 … … 1306 1330 1307 1331 :: 1308 1332 1309 sage: p = polar_plot(2 + 2*cos(x), 0, 2*pi, rgbcolor=hue(0.3))1333 sage: p = polar_plot(2 + 2*cos(x), 0, 2*pi, color=hue(0.3)) 1310 1334 sage: p.show(gridlines=True, \ 1311 1335 ... hgridlinesstyle=dict(color="orange", linewidth=1.0), \ 1312 1336 ... vgridlinesstyle=dict(color="blue", linestyle=":")) … … 1324 1348 ... (0,{"color":"blue","linestyle":"--"}) 1325 1349 ... ], 1326 1350 ... [ 1327 ... (-1,{" rgbcolor":"red","linestyle":":"}),1351 ... (-1,{"color":"red","linestyle":":"}), 1328 1352 ... (0,{"color":"blue","linestyle":"--"}), 1329 ... (1,{" rgbcolor":"red","linestyle":":"}),1353 ... (1,{"color":"red","linestyle":":"}), 1330 1354 ... ] 1331 1355 ... ), 1332 ... gridlinesstyle=dict(marker='x', rgbcolor="black"))1356 ... gridlinesstyle=dict(marker='x',color="black")) 1333 1357 1334 1358 Grid lines can be added to contour plots. 1335 1359 … … 1337 1361 1338 1362 sage: f = sin(x^2 + y^2)*cos(x)*sin(y) 1339 1363 sage: c = contour_plot(f, (x, -4, 4), (y, -4, 4), plot_points=100) 1340 sage: c.show(gridlines=True, gridlinesstyle={'linestyle':':','linewidth':1, ' rgbcolor':'red'})1364 sage: c.show(gridlines=True, gridlinesstyle={'linestyle':':','linewidth':1, 'color':'red'}) 1341 1365 1342 1366 Grid lines can be added to matrix plots. 1343 1367 … … 1345 1369 1346 1370 sage: M = MatrixSpace(QQ,10).random_element() 1347 1371 sage: matrix_plot(M).show(gridlines=True) 1372 1373 By default, Sage increases the horizontal and vertical axes 1374 limits by a certain percentage in all directions. This is 1375 controlled by the ``axes_pad`` parameter. Increasing the range 1376 of the axes helps avoid problems with lines and dots being 1377 clipped because the linewidth extends beyond the axes. To get 1378 axes limits that are exactly what is specified, set 1379 ``axes_pad`` to zero. Compare the following two examples 1380 1381 :: 1382 1383 sage: plot(sin(x), (x, -pi, pi),thickness=2)+point((pi, -1), pointsize=15) 1384 sage: plot(sin(x), (x, -pi, pi),thickness=2,axes_pad=0)+point((pi, -1), pointsize=15) 1385 1348 1386 """ 1349 1387 1350 1388 # This option should not be passed on to save(). … … 1491 1529 ymax += 1 1492 1530 return {'xmin':xmin, 'xmax':xmax, 'ymin':ymin, 'ymax':ymax} 1493 1531 1494 def save(self, filename=None,1532 def matplotlib(self, filename=None, 1495 1533 xmin=None, xmax=None, ymin=None, ymax=None, 1496 figsize= DEFAULT_FIGSIZE, figure=None, sub=None, savenow=True,1497 dpi=DEFAULT_DPI,axes=None, axes_labels=None, fontsize=None,1534 figsize=None, figure=None, sub=None, 1535 axes=None, axes_labels=None, fontsize=None, 1498 1536 frame=False, verify=True, aspect_ratio = None, 1499 1537 gridlines=None, gridlinesstyle=None, 1500 vgridlinesstyle=None, hgridlinesstyle=None): 1538 vgridlinesstyle=None, hgridlinesstyle=None,axes_pad=0.02): 1539 r""" 1540 Return a matplotlib figure object representing the graphic 1541 1542 EXAMPLES:: 1543 1544 sage: c = circle((1,1),1) 1545 sage: print c.matplotlib() 1546 Figure(480x296.656) 1547 1548 To obtain the first matplotlib axes object inside of the 1549 figure, you can do something like the following. 1550 1551 :: 1552 1553 sage: p=plot(sin(x), (x, -2*pi, 2*pi)) 1554 sage: figure=p.matplotlib() 1555 sage: axes=figure.axes[0] 1556 1557 For input parameters, see the documentation for the 1558 :meth:`show` method (this function accepts all except the 1559 transparent argument). 1560 """ 1561 self.set_axes_range(xmin, xmax, ymin, ymax) 1562 d = self.get_axes_range() 1563 xmin = d['xmin'] 1564 xmax = d['xmax'] 1565 ymin = d['ymin'] 1566 ymax = d['ymax'] 1567 1568 x_pad=(xmax-xmin)*float(axes_pad) 1569 y_pad=(ymax-ymin)*float(axes_pad) 1570 1571 xmin-=x_pad 1572 xmax+=x_pad 1573 ymin-=y_pad 1574 ymax+=y_pad 1575 1576 self.set_axes_range(xmin,xmax,ymin,ymax) 1577 1578 global do_verify 1579 do_verify = verify 1580 1581 if axes is None: 1582 axes = self.__show_axes 1583 1584 from matplotlib.figure import Figure, figaspect 1585 self.fontsize(fontsize) 1586 self.axes_labels(l=axes_labels) 1587 1588 # adjust the figsize in case the user also specifies an aspect ratio 1589 if aspect_ratio is None: 1590 aspect_ratio = self.aspect_ratio() 1591 1592 # We try to accommodate both a demand for aspect ratio and 1593 # for a figure size by adjusting the figure size to have 1594 # the right aspect ratio. 1595 if figsize is None: 1596 figsize=DEFAULT_FIGSIZE 1597 figsize=adjust_figsize_for_aspect_ratio(figsize, aspect_ratio, 1598 xmin=xmin, xmax=xmax, 1599 ymin=ymin, ymax=ymax) 1600 1601 if figure is None: 1602 figure=Figure(figsize) 1603 1604 #the incoming subplot instance 1605 subplot = sub 1606 if not subplot: 1607 subplot = figure.add_subplot(111) 1608 if aspect_ratio is not None: 1609 subplot.set_aspect('auto') 1610 1611 #add all the primitives to the subplot 1612 for g in self.__objects: 1613 g._render_on_subplot(subplot) 1614 1615 1616 subplot.set_xlim([xmin, xmax]) 1617 subplot.set_ylim([ymin,ymax]) 1618 1619 if axes is None: 1620 axes = self.__show_axes 1621 1622 for spine in subplot.spines.values(): 1623 spine.set_color(self.__axes_color) 1624 spine.set_linewidth(self.__axes_width) 1625 1626 1627 if frame: 1628 # For now, set the formatter to the old one, since that is 1629 # sort of what we are used to. We should eventually look at 1630 # the default one to see if we like it better. 1631 from matplotlib.ticker import OldScalarFormatter, MaxNLocator 1632 subplot.xaxis.set_major_locator(MaxNLocator(nbins=9)) 1633 subplot.yaxis.set_major_locator(MaxNLocator(nbins=9)) 1634 subplot.xaxis.set_major_formatter(OldScalarFormatter()) 1635 subplot.yaxis.set_major_formatter(OldScalarFormatter()) 1636 1637 subplot.set_frame_on(True) 1638 if axes: 1639 if ymin<=0 and ymax>=0: 1640 subplot.axhline(color=self.__axes_color, 1641 linewidth=self.__axes_width) 1642 if xmin<=0 and xmax>=0: 1643 subplot.axvline(color=self.__axes_color, 1644 linewidth=self.__axes_width) 1645 1646 elif axes: 1647 ymiddle=False 1648 xmiddle=False 1649 if xmin>0: 1650 subplot.spines['right'].set_visible(False) 1651 subplot.spines['left'].set_position(('outward',10)) 1652 subplot.yaxis.set_ticks_position('left') 1653 subplot.yaxis.set_label_position('left') 1654 yaxis='left' 1655 elif xmax<0: 1656 subplot.spines['left'].set_visible(False) 1657 subplot.spines['right'].set_position(('outward',10)) 1658 subplot.yaxis.set_ticks_position('right') 1659 subplot.yaxis.set_label_position('right') 1660 yaxis='right' 1661 else: 1662 subplot.spines['left'].set_position('zero') 1663 subplot.yaxis.set_ticks_position('left') 1664 subplot.yaxis.set_label_position('left') 1665 subplot.spines['right'].set_visible(False) 1666 ymiddle=True 1667 yaxis='left' 1668 1669 if ymin>0: 1670 subplot.spines['top'].set_visible(False) 1671 subplot.spines['bottom'].set_position(('outward',10)) 1672 subplot.xaxis.set_ticks_position('bottom') 1673 subplot.xaxis.set_label_position('bottom') 1674 xaxis='bottom' 1675 elif ymax<0: 1676 subplot.spines['bottom'].set_visible(False) 1677 subplot.spines['top'].set_position(('outward',10)) 1678 subplot.xaxis.set_ticks_position('top') 1679 subplot.xaxis.set_label_position('top') 1680 xaxis='top' 1681 else: 1682 subplot.spines['bottom'].set_position('zero') 1683 subplot.xaxis.set_ticks_position('bottom') 1684 subplot.xaxis.set_label_position('bottom') 1685 subplot.spines['top'].set_visible(False) 1686 xmiddle=True 1687 xaxis='bottom' 1688 1689 # For now, set the formatter to the old one, since that is 1690 # sort of what we are used to. We should eventually look at 1691 # the default one to see if we like it better. 1692 from matplotlib.ticker import OldScalarFormatter, MaxNLocator 1693 subplot.xaxis.set_major_locator(MaxNLocator(nbins=10,steps=[1,2,5,10])) 1694 subplot.yaxis.set_major_locator(MaxNLocator(nbins=10,steps=[1,2,5,10])) 1695 subplot.xaxis.set_major_formatter(OldScalarFormatter()) 1696 subplot.yaxis.set_major_formatter(OldScalarFormatter()) 1697 1698 1699 # Make ticklines go on both sides of the axes 1700 # if xmiddle: 1701 # for t in subplot.xaxis.get_majorticklines(): 1702 # t.set_marker("|") 1703 # t.set_markersize(8) 1704 # for t in subplot.xaxis.get_minorticklines(): 1705 # t.set_marker("|") 1706 # t.set_markersize(4) 1707 1708 # if ymiddle: 1709 # for t in subplot.yaxis.get_majorticklines(): 1710 # t.set_marker("|") 1711 # t.set_markersize(8) 1712 # for t in subplot.yaxis.get_minorticklines(): 1713 # t.set_marker("|") 1714 # t.set_markersize(4) 1715 1716 # Make the zero tick labels disappear if the axes cross 1717 # inside the picture 1718 if xmiddle and ymiddle: 1719 subplot.yaxis.set_major_formatter(SelectiveFormatter(subplot.yaxis.get_major_formatter(),skip_values=[0])) 1720 subplot.xaxis.set_major_formatter(SelectiveFormatter(subplot.xaxis.get_major_formatter(),skip_values=[0])) 1721 1722 else: 1723 for spine in subplot.spines.values(): 1724 spine.set_visible(False) 1725 from matplotlib.ticker import NullFormatter, NullLocator 1726 subplot.xaxis.set_major_formatter(NullFormatter()) 1727 subplot.yaxis.set_major_formatter(NullFormatter()) 1728 subplot.xaxis.set_major_locator(NullLocator()) 1729 subplot.yaxis.set_major_locator(NullLocator()) 1730 1731 if frame or axes: 1732 # Make minor tickmarks 1733 from matplotlib.ticker import AutoMinorLocator 1734 subplot.xaxis.set_minor_locator(AutoMinorLocator()) 1735 subplot.yaxis.set_minor_locator(AutoMinorLocator()) 1736 1737 ticklabels=subplot.xaxis.get_majorticklabels() + \ 1738 subplot.xaxis.get_minorticklabels() + \ 1739 subplot.yaxis.get_majorticklabels() + \ 1740 subplot.yaxis.get_minorticklabels() 1741 for ticklabel in ticklabels: 1742 ticklabel.set_fontsize(self.__fontsize) 1743 ticklabel.set_color(self.__tick_label_color) 1744 1745 ticklines=subplot.xaxis.get_majorticklines() + \ 1746 subplot.xaxis.get_minorticklines() + \ 1747 subplot.yaxis.get_majorticklines() + \ 1748 subplot.yaxis.get_minorticklines() 1749 for tickline in ticklines: 1750 tickline.set_color(self.__axes_color) 1751 1752 1753 if gridlines is not None: 1754 if isinstance(gridlines, (list, tuple)): 1755 vgridlines,hgridlines=gridlines 1756 else: 1757 hgridlines=gridlines 1758 vgridlines=gridlines 1759 1760 if gridlinesstyle is None: 1761 # Set up the default grid style 1762 gridlinesstyle=dict(color='black',linestyle=':',linewidth=0.5) 1763 1764 vgridstyle=gridlinesstyle.copy() 1765 if vgridlinesstyle is not None: 1766 vgridstyle.update(vgridlinesstyle) 1767 1768 hgridstyle=gridlinesstyle.copy() 1769 if hgridlinesstyle is not None: 1770 hgridstyle.update(hgridlinesstyle) 1771 1772 if hgridlines=="minor": 1773 hgridstyle['which']="minor" 1774 if vgridlines=="minor": 1775 vgridstyle['which']="minor" 1776 1777 if hasattr(hgridlines, '__iter__'): 1778 hlines=iter(hgridlines) 1779 hgridstyle.pop("minor",None) 1780 for hline in hlines: 1781 if isinstance(hline, (list, tuple)): 1782 hl, style=hline 1783 st=hgridstyle.copy() 1784 st.update(style) 1785 else: 1786 hl=hline 1787 st=hgridstyle 1788 subplot.axhline(hl,**st) 1789 else: 1790 if hgridlines not in (None, False): 1791 subplot.yaxis.grid(True, **hgridstyle) 1792 1793 if hasattr(vgridlines, '__iter__'): 1794 vlines=iter(vgridlines) 1795 vgridstyle.pop("minor",None) 1796 for vline in vlines: 1797 if isinstance(vline, (list, tuple)): 1798 vl, style=vline 1799 st=vgridstyle.copy() 1800 st.update(style) 1801 else: 1802 vl=vline 1803 st=vgridstyle 1804 subplot.axvline(vl,**st) 1805 else: 1806 if vgridlines not in (None, False): 1807 subplot.xaxis.grid(True, **vgridstyle) 1808 1809 if aspect_ratio is not None: 1810 subplot.set_aspect(aspect_ratio) 1811 1812 1813 if self.__axes_labels is not None: 1814 label_options={} 1815 label_options['color']=self.__axes_label_color 1816 label_options['size']=self.__fontsize 1817 subplot.set_xlabel(self.__axes_labels[0], **label_options) 1818 subplot.set_ylabel(self.__axes_labels[1], **label_options) 1819 1820 1821 if axes is True and frame is False: 1822 # We set the label positions according to where we are 1823 # drawing the axes. 1824 if xaxis=='bottom': 1825 yaxis_labely=1 1826 yaxis_labeloffset=8 1827 yaxis_vert='bottom' 1828 xaxis_labely=0 1829 xaxis_vert='baseline' 1830 else: 1831 yaxis_labely=0 1832 yaxis_labeloffset=-8 1833 yaxis_vert='top' 1834 xaxis_labely=1 1835 xaxis_vert='top' 1836 1837 if yaxis=='left': 1838 xaxis_labelx=1 1839 xaxis_labeloffset=8 1840 xaxis_horiz='left' 1841 yaxis_labelx=0 1842 else: 1843 xaxis_labelx=0 1844 xaxis_labeloffset=-8 1845 xaxis_horiz='right' 1846 yaxis_labelx=1 1847 1848 from matplotlib.transforms import offset_copy 1849 xlabel=subplot.xaxis.get_label() 1850 xlabel.set_horizontalalignment(xaxis_horiz) 1851 xlabel.set_verticalalignment(xaxis_vert) 1852 trans=subplot.spines[xaxis].get_transform() 1853 labeltrans=offset_copy(trans, figure, x=xaxis_labeloffset, y=0, units='points') 1854 subplot.xaxis.set_label_coords(x=xaxis_labelx,y=xaxis_labely,transform=labeltrans) 1855 1856 ylabel=subplot.yaxis.get_label() 1857 ylabel.set_horizontalalignment('center') 1858 ylabel.set_verticalalignment(yaxis_vert) 1859 ylabel.set_rotation('horizontal') 1860 trans=subplot.spines[yaxis].get_transform() 1861 labeltrans=offset_copy(trans, figure, x=0, y=yaxis_labeloffset, units='points') 1862 subplot.yaxis.set_label_coords(x=yaxis_labelx,y=yaxis_labely,transform=labeltrans) 1863 1864 #subplot.autoscale_view(tight=True) 1865 return figure 1866 1867 def save(self, filename=None, dpi=DEFAULT_DPI, savenow=True, *args, **kwds): 1501 1868 r""" 1502 1869 Save the graphics to an image file of type: PNG, PS, EPS, SVG, 1503 1870 SOBJ, depending on the file extension you give the filename. … … 1505 1872 ``.eps``, ``.svg``, and 1506 1873 ``.sobj`` (for a Sage object you can load later). 1507 1874 1875 1508 1876 EXAMPLES:: 1509 1877 1510 sage: c = circle((1,1),1, rgbcolor=(1,0,0))1878 sage: c = circle((1,1),1,color='red') 1511 1879 sage: c.show(xmin=-1,xmax=3,ymin=-1,ymax=3) 1512 1880 1513 To correct the aspect ratio of certain graphics, it is necessary to1514 s how with a '``figsize``' of square dimensions.1881 To correct the aspect ratio of certain graphics, you can 1882 set the ``aspect_ratio`` to 1 1515 1883 1516 1884 :: 1517 1885 1518 sage: c.show(figsize=[5,5],xmin=-1,xmax=3,ymin=-1,ymax=3) 1886 sage: c.show(aspect_ratio=1, xmin=-1, xmax=3, ymin=-1, ymax=3) 1887 1888 You could also just make the dimensions of the picture square 1889 using ``figsize`` 1890 1891 :: 1892 1893 sage: c.show(figsize=[5,5], xmin=-1, xmax=3, ymin=-1, ymax=3) 1894 1895 1519 1896 1520 1897 :: 1521 1898 1522 sage: point((-1,1),pointsize=30, rgbcolor=(1,0,0)) 1899 sage: point((-1,1),pointsize=30, color='red') 1900 1901 By default, the figure grows to include all of the graphics 1902 and text, so the final image may not be exactly the figure 1903 size you specified. 1523 1904 """ 1524 self.set_axes_range(xmin, xmax, ymin, ymax)1525 d = self.get_axes_range()1526 xmin = d['xmin']1527 xmax = d['xmax']1528 ymin = d['ymin']1529 ymax = d['ymax']1530 1531 # adjust the figsize in case the user also specifies an aspect ratio1532 if aspect_ratio is None:1533 aspect_ratio = self.aspect_ratio()1534 figsize = adjust_figsize_for_aspect_ratio(figsize, aspect_ratio, xmin=xmin,1535 xmax=xmax, ymin=ymin, ymax=ymax)1536 1537 global do_verify1538 do_verify = verify1539 1540 if axes is None:1541 axes = self.__show_axes1542 1543 from matplotlib.figure import Figure1544 1905 if filename is None: 1545 1906 filename = sage.misc.misc.graphics_filename() 1546 1907 try: … … 1552 1913 SageObject.save(self, filename) 1553 1914 return 1554 1915 1555 self.fontsize(fontsize) 1556 self.axes_labels(l=axes_labels) 1916 if savenow: 1917 options=dict() 1918 options['transparent']=kwds.pop('transparent',False) 1919 figure=self.matplotlib(*args, **kwds) 1920 # You can output in PNG, PS, EPS, PDF, or SVG format, depending on the file extension. 1921 # matplotlib looks at the file extension to see what the renderer should be. 1922 # The default is FigureCanvasAgg for PNG's because this is by far the most 1923 # common type of files rendered, like in the notebook, for example. 1924 # if the file extension is not '.png', then matplotlib will handle it. 1925 from matplotlib.backends.backend_agg import FigureCanvasAgg 1926 figure.set_canvas(FigureCanvasAgg(figure)) 1557 1927 1558 if figure is None:1559 figure = Figure(figsize)1560 1561 #The line below takes away the excessive whitespace around1562 #images. ('figsize' and 'dpi' still work as expected):1563 figure.subplots_adjust(left=0.04, bottom=0.04, right=0.96, top=0.96)1564 1565 #the incoming subplot instance1566 subplot = sub1567 if not subplot:1568 subplot = figure.add_subplot(111)1569 1570 #take away the matplotlib axes:1571 subplot.xaxis.set_visible(False)1572 subplot.yaxis.set_visible(False)1573 subplot.set_frame_on(False)1574 1575 #add all the primitives to the subplot1576 #check if there are any ContourPlot instances1577 #in self._objects, and if so change the axes1578 #to be frame axes instead of centered axes1579 contour = False1580 plotfield = False1581 matrixplot = False1582 from contour_plot import ContourPlot1583 from matrix_plot import MatrixPlot1584 from plot_field import PlotField1585 for g in self.__objects:1586 if isinstance(g, ContourPlot):1587 contour = True1588 if isinstance(g, PlotField):1589 plotfield = True1590 if isinstance(g, MatrixPlot):1591 matrixplot = True1592 g._render_on_subplot(subplot)1593 1594 #adjust the xy limits and draw the axes:1595 if axes is None:1596 axes = self.__show_axes1597 1598 #construct an Axes instance, see 'axes.py' for relevant code1599 sage_axes = Axes(color=self.__axes_color, fontsize=self.__fontsize,1600 axes_labels=self.__axes_labels,1601 axes_label_color=self.__axes_label_color,1602 tick_label_color=self.__tick_label_color, linewidth=self.__axes_width)1603 1604 # construct a GridLines instance, see 'axes.py' for relevant code1605 sage_gridlines = GridLines(gridlines=gridlines, gridlinesstyle=gridlinesstyle,1606 vgridlinesstyle=vgridlinesstyle, hgridlinesstyle=hgridlinesstyle)1607 1608 #adjust the xy limits and draw the axes:1609 if not (contour or plotfield or matrixplot): #the plot is a 'regular' plot1610 xmin -= 0.1*(xmax-xmin)1611 xmax += 0.1*(xmax-xmin)1612 ymin -= 0.1*(ymax-ymin)1613 ymax += 0.1*(ymax-ymin)1614 if frame: #add the frame axes1615 axmin, axmax = xmin - 0.04*abs(xmax - xmin), xmax + 0.04*abs(xmax - xmin)1616 aymin, aymax = ymin - 0.04*abs(ymax - ymin), ymax + 0.04*abs(ymax - ymin)1617 subplot.set_xlim([axmin, axmax])1618 subplot.set_ylim([aymin, aymax])1619 # draw the grid1620 sage_gridlines.add_gridlines(subplot, xmin, xmax, ymin, ymax, True)1621 #add a frame to the plot and possibly 'axes_with_no_ticks'1622 sage_axes.add_xy_frame_axes(subplot, xmin, xmax, ymin, ymax,1623 axes_with_no_ticks=axes)1624 1625 elif not frame and axes: #regular plot with regular axes1626 # draw the grid1627 sage_gridlines.add_gridlines(subplot, xmin, xmax, ymin, ymax, False)1628 # draw the axes1629 xmin, xmax, ymin, ymax = sage_axes.add_xy_axes(subplot, xmin, xmax, ymin, ymax)1630 subplot.set_xlim(xmin, xmax)1631 subplot.set_ylim(ymin, ymax)1632 1633 else: #regular plot with no axes1634 subplot.set_xlim(xmin, xmax)1635 subplot.set_ylim(ymin, ymax)1636 # draw the grid1637 sage_gridlines.add_gridlines(subplot, xmin, xmax, ymin, ymax, False)1638 1639 elif (contour or plotfield): #contour or field plot in self.__objects, so adjust axes accordingly1640 subplot.set_xlim([xmin - 0.05*abs(xmax - xmin), xmax + 0.05*abs(xmax - xmin)])1641 subplot.set_ylim([ymin - 0.05*abs(ymax - ymin), ymax + 0.05*abs(ymax - ymin)])1642 # draw the grid1643 sage_gridlines.add_gridlines(subplot, xmin, xmax, ymin, ymax, True)1644 # draw the axes1645 if axes: #axes=True unless user specifies axes=False1646 sage_axes.add_xy_frame_axes(subplot, xmin, xmax, ymin, ymax)1647 1648 else: #we have a 'matrix_plot' in self.__objects, so adjust axes accordingly1649 subplot.set_xlim([xmin - 0.05*abs(xmax - xmin), xmax + 0.05*abs(xmax - xmin)])1650 subplot.set_ylim([ymin - 0.05*abs(ymax - ymin), ymax + 0.05*abs(ymax - ymin)])1651 # draw the grid1652 if gridlines in ["major", "automatic", True]:1653 gridlines = [sage.misc.misc.srange(-0.5,xmax+1,1),1654 sage.misc.misc.srange(-0.5,ymax+1,1)]1655 sage_gridlines = GridLines(gridlines=gridlines,1656 gridlinesstyle=gridlinesstyle,1657 vgridlinesstyle=vgridlinesstyle,1658 hgridlinesstyle=hgridlinesstyle)1659 sage_gridlines.add_gridlines(subplot, xmin, xmax, ymin, ymax, False)1660 # draw the axes1661 if axes: #axes=True unless user specifies axes=False1662 sage_axes.add_xy_matrix_frame_axes(subplot, xmin, xmax, ymin, ymax)1663 1664 # You can output in PNG, PS, EPS, PDF, or SVG format, depending on the file extension.1665 # matplotlib looks at the file extension to see what the renderer should be.1666 # The default is FigureCanvasAgg for PNG's because this is by far the most1667 # common type of files rendered, like in the Notebook for example.1668 # if the file extension is not '.png', then matplotlib will handle it.1669 if savenow:1670 from matplotlib.backends.backend_agg import FigureCanvasAgg1671 canvas = FigureCanvasAgg(figure)1672 1928 if ext in ['.eps', '.ps', '.pdf']: 1673 1929 if dpi is None: 1674 1930 dpi = 72 … … 1680 1936 dpi = 100 1681 1937 else: 1682 1938 raise ValueError, "file extension must be either 'png', 'ps, 'eps', 'pdf, 'svg' or 'sobj'" 1683 canvas.print_figure(filename, dpi=dpi) 1939 figure.savefig(filename,dpi=dpi,bbox_inches='tight',**options) 1940 1941 1942 1943 from matplotlib.ticker import Formatter 1944 1945 class SelectiveFormatter(Formatter): 1946 """ 1947 This matplotlib formatter selectively omits some tick values and 1948 passes the rest on to a specified formatter. 1949 1950 EXAMPLES: 1951 1952 This example is almost straight from a matplotlib example. 1953 1954 :: 1955 1956 sage: from sage.plot.plot import SelectiveFormatter 1957 sage: import matplotlib.pyplot as plt 1958 sage: import numpy 1959 sage: fig=plt.figure() 1960 sage: ax=fig.add_subplot(111) 1961 sage: t = numpy.arange(0.0, 2.0, 0.01) 1962 sage: s = numpy.sin(2*numpy.pi*t) 1963 sage: line=ax.plot(t, s) 1964 sage: formatter=SelectiveFormatter(ax.xaxis.get_major_formatter(),skip_values=[0,1]) 1965 sage: ax.xaxis.set_major_formatter(formatter) 1966 sage: fig.savefig('test.png') 1967 """ 1968 def __init__(self, formatter,skip_values): 1969 """ 1970 Initialize a SelectiveFormatter object. 1971 1972 INPUT: 1973 1974 - formatter -- the formatter object to which we should pass labels 1975 1976 - skip_values -- a list of values that we should skip when 1977 formatting the tick labels 1978 1979 EXAMPLES:: 1980 1981 sage: from sage.plot.plot import SelectiveFormatter 1982 sage: import matplotlib.pyplot as plt 1983 sage: import numpy 1984 sage: fig=plt.figure() 1985 sage: ax=fig.add_subplot(111) 1986 sage: t = numpy.arange(0.0, 2.0, 0.01) 1987 sage: s = numpy.sin(2*numpy.pi*t) 1988 sage: line=ax.plot(t, s) 1989 sage: formatter=SelectiveFormatter(ax.xaxis.get_major_formatter(),skip_values=[0,1]) 1990 sage: ax.xaxis.set_major_formatter(formatter) 1991 sage: fig.savefig('test.png') 1992 """ 1993 self.formatter=formatter 1994 self.skip_values=skip_values 1995 def set_locs(self, locs): 1996 """ 1997 Set the locations for the ticks that are not skipped. 1998 1999 EXAMPLES:: 2000 sage: from sage.plot.plot import SelectiveFormatter 2001 sage: import matplotlib.ticker 2002 sage: formatter=SelectiveFormatter(matplotlib.ticker.Formatter(),skip_values=[0,200]) 2003 sage: formatter.set_locs([i*100 for i in range(10)]) 2004 """ 2005 self.formatter.set_locs([l for l in locs if l not in self.skip_values]) 2006 def __call__(self, x, *args, **kwds): 2007 """ 2008 Return the format for tick val *x* at position *pos* 2009 2010 EXAMPLES:: 2011 2012 sage: from sage.plot.plot import SelectiveFormatter 2013 sage: import matplotlib.ticker 2014 sage: formatter=SelectiveFormatter(matplotlib.ticker.FixedFormatter(['a','b']),skip_values=[0,2]) 2015 sage: [formatter(i,1) for i in range(10)] 2016 ['', 'b', '', 'b', 'b', 'b', 'b', 'b', 'b', 'b'] 2017 """ 2018 if x in self.skip_values: 2019 return '' 2020 else: 2021 return self.formatter(x, *args, **kwds) 2022 1684 2023 1685 2024 def xydata_from_point_list(points): 1686 2025 r""" … … 1862 2201 1863 2202 Some colored functions:: 1864 2203 1865 sage: plot(sin, 0, 10, rgbcolor='#ff00ff')1866 sage: plot(sin, 0, 10, rgbcolor='purple')2204 sage: plot(sin, 0, 10, color='purple') 2205 sage: plot(sin, 0, 10, color='#ff00ff') 1867 2206 1868 2207 We plot several functions together by passing a list of functions 1869 2208 as input:: … … 1885 2224 The algorithm used to insert extra points is actually pretty 1886 2225 simple. On the picture drawn by the lines below:: 1887 2226 1888 sage: p = plot(x^2, (-0.5, 1.4)) + line([(0,0), (1,1)], rgbcolor='green')1889 sage: p += line([(0.5, 0.5), (0.5, 0.5^2)], rgbcolor='purple')1890 sage: p += point(((0, 0), (0.5, 0.5), (0.5, 0.5^2), (1, 1)), rgbcolor='red', pointsize=20)1891 sage: p += text('A', (-0.05, 0.1), rgbcolor='red')1892 sage: p += text('B', (1.01, 1.1), rgbcolor='red')1893 sage: p += text('C', (0.48, 0.57), rgbcolor='red')1894 sage: p += text('D', (0.53, 0.18), rgbcolor='red')2227 sage: p = plot(x^2, (-0.5, 1.4)) + line([(0,0), (1,1)], color='green') 2228 sage: p += line([(0.5, 0.5), (0.5, 0.5^2)], color='purple') 2229 sage: p += point(((0, 0), (0.5, 0.5), (0.5, 0.5^2), (1, 1)), color='red', pointsize=20) 2230 sage: p += text('A', (-0.05, 0.1), color='red') 2231 sage: p += text('B', (1.01, 1.1), color='red') 2232 sage: p += text('C', (0.48, 0.57), color='red') 2233 sage: p += text('D', (0.53, 0.18), color='red') 1895 2234 sage: p.show(axes=False, xmin=-0.5, xmax=1.4, ymin=0, ymax=2) 1896 2235 1897 2236 You have the function (in blue) and its approximation (in green) … … 1919 2258 We can also directly plot the elliptic curve:: 1920 2259 1921 2260 sage: E = EllipticCurve([0,-1]) 1922 sage: plot(E, (1, 4), rgbcolor=hue(0.6))2261 sage: plot(E, (1, 4), color=hue(0.6)) 1923 2262 1924 2263 We can change the line style to one of ``'--'`` (two hyphens, yielding 1925 2264 dashed), ``'-.'`` (dash dot), ``'-'`` (solid), ``'steps'``, ``':'`` (dotted):: … … 2160 2499 fillcolor = options.pop('fillcolor', 'automatic') 2161 2500 fillalpha = options.pop('fillalpha', 0.5) 2162 2501 2502 # TODO: Use matplotlib's fill and fill_between commands. 2163 2503 if fill is not None: 2164 2504 if parametric or polar: 2165 2505 filldata = data … … 2280 2620 EXAMPLES: We draw some 2d parametric plots:: 2281 2621 2282 2622 sage: t = var('t') 2283 sage: parametric_plot( (sin(t), sin(2*t)), (t, 0, 2*pi), rgbcolor=hue(0.6) )2623 sage: parametric_plot( (sin(t), sin(2*t)), (t, 0, 2*pi), color=hue(0.6) ) 2284 2624 sage: parametric_plot((1, t), (t, 0, 4)) 2285 2625 2286 2626 Note that in parametric_plot, there is only fill or no fill. … … 2360 2700 2361 2701 A green limacon of Pascal:: 2362 2702 2363 sage: polar_plot(2 + 2*cos(x), (x, 0, 2*pi), rgbcolor=hue(0.3))2703 sage: polar_plot(2 + 2*cos(x), (x, 0, 2*pi), color=hue(0.3)) 2364 2704 2365 2705 Several polar plots:: 2366 2706 … … 2400 2740 Here are a bunch of random red points:: 2401 2741 2402 2742 sage: r = [(random(),random()) for _ in range(20)] 2403 sage: list_plot(r, rgbcolor=(1,0,0))2743 sage: list_plot(r,color='red') 2404 2744 2405 2745 This gives all the random points joined in a purple line:: 2406 2746 2407 sage: list_plot(r, plotjoined=True, rgbcolor=(1,0,1))2747 sage: list_plot(r, plotjoined=True, color='purple') 2408 2748 2409 2749 If you have separate lists of `x` values and `y` values which you 2410 2750 want to plot against each other, use the ``zip`` command to make a … … 2539 2879 do_verify = True 2540 2880 for i,g in zip(range(1, dims+1), glist): 2541 2881 subplot = figure.add_subplot(rows, cols, i) 2542 g. save(filename, dpi=dpi, figure=figure, sub=subplot,2543 savenow = (i==dims), verify=do_verify,2544 axes = axes,2545 **args)#only save if i==dims.2882 g.matplotlib(filename, figure=figure, sub=subplot, 2883 verify=do_verify, axes = axes, **args) 2884 g.save(filename, dpi=dpi, figure=figure, sub=subplot, 2885 verify=do_verify, axes = axes, **args) 2546 2886 2547 2887 def save(self, filename=None, dpi=DEFAULT_DPI, figsize=DEFAULT_FIGSIZE, 2548 2888 axes = None, **args): … … 2647 2987 sage: f(x) = sin(x) 2648 2988 sage: g(x) = sin(2*x) 2649 2989 sage: h(x) = sin(4*x) 2650 sage: p1 = plot(f,-2*pi,2*pi, rgbcolor=hue(0.5))2651 sage: p2 = plot(g,-2*pi,2*pi, rgbcolor=hue(0.9))2652 sage: p3 = parametric_plot((f,g),0,2*pi, rgbcolor=hue(0.6))2653 sage: p4 = parametric_plot((f,h),0,2*pi, rgbcolor=hue(1.0))2990 sage: p1 = plot(f,-2*pi,2*pi,color=hue(0.5)) 2991 sage: p2 = plot(g,-2*pi,2*pi,color=hue(0.9)) 2992 sage: p3 = parametric_plot((f,g),0,2*pi,color=hue(0.6)) 2993 sage: p4 = parametric_plot((f,h),0,2*pi,color=hue(1.0)) 2654 2994 2655 2995 Now make a graphics array out of the plots; then you can type 2656 2996 either: ``ga.show()`` or ``ga.save()``. -
sage/plot/plot_field.py
diff -r 22919ed0d91f -r 91a0bec4200a sage/plot/plot_field.py
a b 126 126 quiver_options.pop('plot_points') 127 127 subplot.quiver(self.xpos_array, self.ypos_array, self.xvec_array, self.yvec_array, angles='xy', **quiver_options) 128 128 129 @options(plot_points=20 )129 @options(plot_points=20,frame=True) 130 130 def plot_vector_field((f, g), xrange, yrange, **options): 131 131 r""" 132 132 ``plot_vector_field`` takes two functions of two variables xvar and yvar -
sage/plot/point.py
diff -r 22919ed0d91f -r 91a0bec4200a sage/plot/point.py
a b 268 268 faceted = options['faceted'] #faceted=True colors the edge of point 269 269 scatteroptions={} 270 270 if not faceted: scatteroptions['edgecolors'] = 'none' 271 272 271 subplot.scatter(self.xdata, self.ydata, s=s, c=c, alpha=a, **scatteroptions) 272 273 273 274 274 def point(points, **kwds): 275 275 """ … … 300 300 from sage.plot.plot3d.shapes2 import point3d 301 301 return point3d(points, **kwds) 302 302 303 @rename_keyword(color='rgbcolor') 303 304 @options(alpha=1, pointsize=10, faceted=False, rgbcolor=(0,0,1)) 304 305 def point2d(points, **options): 305 306 r""" -
sage/plot/polygon.py
diff -r 22919ed0d91f -r 91a0bec4200a sage/plot/polygon.py
a b 263 263 from sage.plot.plot3d.shapes2 import polygon3d 264 264 return polygon3d(points, **options) 265 265 266 @rename_keyword(color='rgbcolor') 266 267 @options(alpha=1, rgbcolor=(0,0,1), thickness=0) 267 268 def polygon2d(points, **options): 268 269 r""" -
sage/plot/text.py
diff -r 22919ed0d91f -r 91a0bec4200a sage/plot/text.py
a b 168 168 opts['transform'] = subplot.transAxes 169 169 subplot.text(self.x, self.y, self.string, **opts) 170 170 171 171 @rename_keyword(color='rgbcolor') 172 172 @options(fontsize=10, rgbcolor=(0,0,1), horizontal_alignment='center', 173 173 vertical_alignment='center', axis_coords=False) 174 174 def text(string, xy, **options):