Ticket #5448: trac-5448-matplotlib-axes-gridlines.4.patch

File trac-5448-matplotlib-axes-gridlines.4.patch, 54.4 KB (added by jason, 11 years ago)

apply instead of previous patches

  • 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  
    11r"""
    222D Axes
    33
     4This module is deprecated and will be removed from a future version of
     5Sage.  The axes and gridline functionality is now taken care of by
     6matplotlib constructs.
     7
    48Sage provides several different axes for its 2D plotting functionality.
    59The 'look' of the axes are similar to what Mathematica provides for its
    6102D plotting.
     
    2933import sage.misc.misc
    3034from copy import copy
    3135
     36from sage.misc.misc import deprecation
     37deprecation('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
    3240class Axes(SageObject):
    3341    """
    3442    Axes for Sage 2-D Graphics.
     
    4048    add_xy_matrix_frame_axes
    4149
    4250    """
     51
    4352    def __init__(self, color=(0,0,0), fontsize=8, linewidth=0.6,axes_labels=None,
    4453                 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.')
    4555        self.__color = color
    4656        self.__tick_label_color = tick_label_color
    4757        self.__axes_labels = axes_labels
     
    6373
    6474        sage: from sage.plot.axes import Axes
    6575        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.
    6677        sage: A._tasteful_ticks(2^(-20*10),2^(-20*1))
    6778        ([1.9999999999999999e-07,  3.9999999999999998e-07,  5.9999999999999997e-07,  7.9999999999999996e-07], 1.9999999999999999e-07, 1.9999999999999999e-07)
    6879        """
     
    506517        TESTS:
    507518            sage: from sage.plot.axes import Axes
    508519            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.
    509521            (-11.0, 41.0, 9.5, 35.5)
    510522        """
    511523        xmin = float(xmin); xmax=float(xmax); ymin=float(ymin); ymax=float(ymax)
     
    645657
    646658        TESTS:
    647659            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.
    648661            sage: GridLines()
    649662            <class 'sage.plot.axes.GridLines'>
    650663            sage: gl = GridLines(False)
     
    658671            sage: gl = GridLines([range(-10,10,2), lambda x,y:srange(x,y,0.5)])
    659672            sage: gl = GridLines(None, dict(color="red"),
    660673            ...     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.
    661675            sage: gl = GridLines(None, dict(rgbcolor="red"),
    662676            ...     dict(linestyle=":"), dict(color="blue"))
    663677        """
     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.')
    664679        self.__gridlines = gridlines
    665680
    666681        defaultstyle = dict(color=(0.3,0.3,0.3),linewidth=0.4)
     
    698713
    699714            sage: subplot = Figure().add_subplot(111)
    700715            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.
    701717            sage: len(subplot.lines)
    702718            0
    703719
     
    708724
    709725            sage: subplot = Figure().add_subplot(111)
    710726            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.
    711728            sage: len(subplot.lines)
    712729            13
    713730
     
    750767            sage: GridLines("automatic", dict(color="red"),
    751768            ...     dict(linestyle=":"),
    752769            ...     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.
    753771            sage: len(subplot.lines)
    754772            13
    755773
     
    856874        TESTS:
    857875            sage: from sage.plot.axes import GridLines
    858876            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.
    859878            [-10, -5, 0, 5, 10, 15, 20]
    860879            sage: GridLines()._get_ticks_locations([10,35],"minor")
    861880            [10.0, 11.0, 12.0, 13.0, ..., 32.0, 33.0, 34.0, 35.0]
     
    884903        TESTS:
    885904            sage: from sage.plot.axes import GridLines
    886905            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.
    887907            (-11.0, 41.0, 9.5, 35.5)
    888908        """
    889909        return Axes()._adjustments_for_frame(*(xinterval+yinterval))
  • sage/plot/bar_chart.py

    diff -r 22919ed0d91f -r 91a0bec4200a sage/plot/bar_chart.py
    a b  
    108108        datalist = numpy.array(self.datalist, dtype=float)
    109109        subplot.bar(ind, datalist, color=color, width=width)
    110110
     111@rename_keyword(color='rgbcolor')
    111112@options(width=0.5, rgbcolor=(0,0,1))
    112113def bar_chart(datalist, **options):
    113114    """
  • sage/plot/bezier_path.py

    diff -r 22919ed0d91f -r 91a0bec4200a sage/plot/bezier_path.py
    a b  
    173173                'ymin': self.vertices[:,1].min(),
    174174                'ymax': self.vertices[:,1].max()}
    175175
     176@rename_keyword(color='rgbcolor')
    176177@options(alpha=1, fill=False, thickness=1, rgbcolor=(0,0,0), zorder=2, linestyle='solid')
    177178def bezier_path(path, **options):
    178179    """
  • sage/plot/circle.py

    diff -r 22919ed0d91f -r 91a0bec4200a sage/plot/circle.py
    a b  
    205205            from line import Line
    206206            return Line(xdata, ydata, options).plot3d().translate((0,0,z))
    207207
    208        
     208@rename_keyword(color='rgbcolor')
    209209@options(alpha=1, fill=False, thickness=1, edgecolor='black', facecolor='red', linestyle='solid', zorder=5)
    210210def circle(center, radius, **options):
    211211    """
  • sage/plot/contour_plot.py

    diff -r 22919ed0d91f -r 91a0bec4200a sage/plot/contour_plot.py
    a b  
    161161            else:
    162162                subplot.contour(self.xy_data_array, contours, cmap=cmap, extent=(x0,x1,y0,y1))
    163163
    164 @options(plot_points=25, fill=True, cmap='gray', contours=None)
     164@options(plot_points=25, fill=True, cmap='gray', contours=None,frame=True)
    165165def contour_plot(f, xrange, yrange, **options):
    166166    r"""   
    167167    ``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  
    243243        return line3d(points, **kwds)
    244244
    245245   
     246@rename_keyword(color='rgbcolor')
    246247@options(alpha=1, rgbcolor=(0,0,1), thickness=1)
    247248def line2d(points, **options):
    248249    r"""
  • sage/plot/matrix_plot.py

    diff -r 22919ed0d91f -r 91a0bec4200a sage/plot/matrix_plot.py
    a b  
    156156            subplot.imshow(self.xy_data_array, cmap=cmap, interpolation='nearest', extent=(0,self.xrange[1],0,self.yrange[1]))
    157157
    158158
    159 @options(cmap='gray',marker='.')
     159@options(cmap='gray',marker='.',frame=True)
    160160def matrix_plot(mat, **options):
    161161    r"""
    162162    A plot of a given matrix or 2D array.
  • sage/plot/plot.py

    diff -r 22919ed0d91f -r 91a0bec4200a sage/plot/plot.py
    a b  
    7272
    7373EXAMPLES: We construct a plot involving several graphics objects::
    7474
    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')
    7777    sage: G + P  # show it
    7878
    7979We draw a circle and a curve::
    8080
    81     sage: circle((1,1), 1) + plot(x^2, (0,5))
     81    sage: circle((1,1), 1) + plot(x^2, (x,0,5))
    8282
    8383Notice that the above circle is not round, because the aspect ratio
    8484of the coordinate system is not 1:1. The
    8585``aspect_ratio`` option to show allows us to fix
    8686this::
    8787
    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)
    8989
    9090With an aspect ratio of 2 the circle is squashed half way down (it
    9191looks twice as wide as it does tall)::
    9292
    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)
    9494
    9595Use figsize to set the actual aspect ratio of the rendered image
    9696(i.e., of the frame). For example, this image is twice as many
    9797pixels wide as it is tall::
    9898
    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])
    100100
    101101Next we construct the reflection of the above polygon about the
    102102`y`-axis by iterating over the list of first-coordinates of
     
    104104Polygon; note that `P` is a Graphics object, which consists
    105105of a single polygon)::
    106106
    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')
    108108    sage: Q   # show it
    109109
    110110We combine together different graphics objects using "+"::
     
    135135
    136136    sage: i = CDF.0      # define i this way for maximum speed.
    137137    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))
    139139    sage: print p1 + p2
    140140    Graphics object consisting of 2 graphics primitives
    141141    sage: p1 + p2    # display it
     
    149149    sage: g = Graphics()
    150150    sage: for i in range(60):
    151151    ...    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)
    153153    ...    g = g + p
    154154    ...
    155155    sage: g.show(dpi=200, axes=False)
     
    157157Another graph::
    158158
    159159    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')
    163163    ...
    164164    sage: P.show(ymin=-pi,ymax=pi)
    165165
     
    191191An illustration of integration::
    192192
    193193    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')
    196196    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)
    199199    sage: P    # show the result
    200200
     201
     202
    201203NUMERICAL PLOTTING:
    202204
    203 Sage also provides 2D plotting with an interface that is a likely
    204 very familiar to people doing numerical computation. For example,
     205Sage includes Matplotlib, which provides 2D plotting with an interface
     206that is a likely very familiar to people doing numerical
     207computation. For example,
    205208
    206209::
    207210
     
    259262- William Stein (2008-01-19): raised the documentation coverage from a
    260263  miserable 12 percent to a 'wopping' 35 percent, and fixed and
    261264  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
    262269"""
    263270
    264271############################################################################
     
    348355# Sage startup times are much improved.)  - William
    349356###############
    350357
    351 #Sage 2D Graphics Axes class:
    352 from axes import Axes
    353 from axes import GridLines
    354 
    355358def is_Graphics(x):
    356359    """
    357360    Return True if `x` is a Graphics object.
     
    376379   
    377380        sage: G = Graphics(); print G
    378381        Graphics object consisting of 0 graphics primitives
    379         sage: c = circle((1,1), 1)
     382        sage: c = circle((1,1), 1,aspect_ratio=1)
    380383        sage: G+=c; print G
    381384        Graphics object consisting of 1 graphics primitive
    382385   
    383386    Here we make a graphic of embedded isosceles triangles, coloring
    384387    each one with a different color as we go::
    385388   
    386         sage: h=10; c=0.4; p=0.1;
     389        sage: h=10; c=0.4; p=0.5;
    387390        sage: G = Graphics()
    388391        sage: for x in srange(1,h+1):
    389392        ...        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)))
    391394        sage: G.show(figsize=[5,5])
    392395    """
    393396
     
    683686        ::
    684687       
    685688            sage: p = plot(sin(x), (x, 0, 10))
    686             sage: p.axes_labels(['x','y'])
     689            sage: p.axes_labels(['$x$','$y$'])
    687690            sage: p.axes_labels()
    688             ('x', 'y')
     691            ('$x$', '$y$')
    689692       
    690693        Now when you plot p, you see x and y axes labels::
    691694       
     
    10331036        EXAMPLES::
    10341037       
    10351038            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')
    10371040            sage: g1 + g2  # displays the plot
    10381041
    10391042        TESTS::
     
    11491152                        dpi=DEFAULT_DPI, axes=None, axes_labels=None,frame=False,
    11501153                        fontsize=None, aspect_ratio=None,
    11511154                        gridlines=None, gridlinesstyle=None,
    1152                         vgridlinesstyle=None, hgridlinesstyle=None)
     1155                        vgridlinesstyle=None, hgridlinesstyle=None,transparent=False,
     1156                        axes_pad=.02)
    11531157
    11541158    def show(self, **kwds):
    11551159        """
     
    11841188
    11851189        - ``gridlines`` - (default: None) can be any of the following:
    11861190
    1187           -  None, False: do not add grid lines.
     1191          - None, False: do not add grid lines.
    11881192
    11891193          - True, "automatic", "major": add grid lines at major ticks of the axes.
    11901194
     
    12161220        - ``linkmode`` - (default: False) If True a string containing a link
    12171221            to the produced file is returned.
    12181222
     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
    12191231        EXAMPLES::
    12201232       
    1221             sage: c = circle((1,1), 1, rgbcolor=(1,0,0))
     1233            sage: c = circle((1,1), 1, color='red')
    12221234            sage: c.show(xmin=-1, xmax=3, ymin=-1, ymax=3)
    12231235       
    1224         To correct the aspect ratio of certain graphics, it is necessary to
    1225         show with a '``figsize``' of square dimensions.
     1236        To correct the aspect ratio of certain graphics, you can
     1237        set the ``aspect_ratio`` to 1
    12261238       
    12271239        ::
    12281240       
    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)       
    12301249       
    12311250        You can turn off the drawing of the axes::
    12321251       
    12331252            sage: show(plot(sin,-4,4), axes=False)
    12341253       
    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::
    12361256       
    1237             sage: show(plot(sin,-4,4), axes_labels=('x','y'))
     1257            sage: show(plot(sin,-4,4), axes_labels=('$x$','$y$'))
    12381258       
    12391259        You can turn on the drawing of a frame around the plots::
    12401260       
    12411261            sage: show(plot(sin,-4,4), frame=True)
    12421262       
    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.
    12441268       
    12451269        ::
    12461270       
     
    12811305       
    12821306            sage: def maple_leaf(t):
    12831307            ...     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) #long
     1308            sage: p = polar_plot(maple_leaf, -pi/4, 3*pi/2, color="red",plot_points=1000) #long
    12851309            sage: p.show(gridlines=( [-3,-2.75,..,3], xrange(-1,5,2) )) #long
    12861310       
    12871311        Add grid lines at specific positions (using functions).
     
    12971321       
    12981322        ::
    12991323       
    1300             sage: b = bar_chart([-3,5,-6,11], rgbcolor=(1,0,0))
     1324            sage: b = bar_chart([-3,5,-6,11], color='red')
    13011325            sage: b.show(gridlines=([-1,-0.5,..,4],True), \
    13021326            ...     gridlinesstyle=dict(color="blue", linestyle=":"))
    13031327       
     
    13061330       
    13071331        ::
    13081332       
    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))
    13101334            sage: p.show(gridlines=True, \
    13111335            ...     hgridlinesstyle=dict(color="orange", linewidth=1.0), \
    13121336            ...     vgridlinesstyle=dict(color="blue", linestyle=":"))
     
    13241348            ...     (0,{"color":"blue","linestyle":"--"})
    13251349            ...    ],
    13261350            ...    [
    1327             ...     (-1,{"rgbcolor":"red","linestyle":":"}),
     1351            ...     (-1,{"color":"red","linestyle":":"}),
    13281352            ...     (0,{"color":"blue","linestyle":"--"}),
    1329             ...     (1,{"rgbcolor":"red","linestyle":":"}),
     1353            ...     (1,{"color":"red","linestyle":":"}),
    13301354            ...    ]
    13311355            ...    ),
    1332             ...    gridlinesstyle=dict(marker='x',rgbcolor="black"))
     1356            ...    gridlinesstyle=dict(marker='x',color="black"))
    13331357       
    13341358        Grid lines can be added to contour plots.
    13351359       
     
    13371361       
    13381362            sage: f = sin(x^2 + y^2)*cos(x)*sin(y)
    13391363            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'})
    13411365       
    13421366        Grid lines can be added to matrix plots.
    13431367       
     
    13451369       
    13461370            sage: M = MatrixSpace(QQ,10).random_element()
    13471371            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       
    13481386        """
    13491387
    13501388        # This option should not be passed on to save().
     
    14911529            ymax += 1
    14921530        return {'xmin':xmin, 'xmax':xmax, 'ymin':ymin, 'ymax':ymax}
    14931531       
    1494     def save(self, filename=None,
     1532    def matplotlib(self, filename=None,
    14951533             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,
    14981536             frame=False, verify=True, aspect_ratio = None,
    14991537             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):
    15011868        r"""
    15021869        Save the graphics to an image file of type: PNG, PS, EPS, SVG,
    15031870        SOBJ, depending on the file extension you give the filename.
     
    15051872        ``.eps``, ``.svg``, and
    15061873        ``.sobj`` (for a Sage object you can load later).
    15071874       
     1875
    15081876        EXAMPLES::
    15091877       
    1510             sage: c = circle((1,1),1,rgbcolor=(1,0,0))
     1878            sage: c = circle((1,1),1,color='red')
    15111879            sage: c.show(xmin=-1,xmax=3,ymin=-1,ymax=3)
    15121880       
    1513         To correct the aspect ratio of certain graphics, it is necessary to
    1514         show with a '``figsize``' of square dimensions.
     1881        To correct the aspect ratio of certain graphics, you can
     1882        set the ``aspect_ratio`` to 1
    15151883       
    15161884        ::
    15171885       
    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
    15191896       
    15201897        ::
    15211898       
    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.
    15231904        """
    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 ratio
    1532         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_verify
    1538         do_verify = verify
    1539 
    1540         if axes is None:
    1541             axes = self.__show_axes
    1542 
    1543         from matplotlib.figure import Figure
    15441905        if filename is None:
    15451906            filename = sage.misc.misc.graphics_filename()
    15461907        try:
     
    15521913            SageObject.save(self, filename)
    15531914            return
    15541915
    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))
    15571927
    1558         if figure is None:
    1559             figure = Figure(figsize)
    1560 
    1561         #The line below takes away the excessive whitespace around
    1562         #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 instance
    1566         subplot = sub
    1567         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 subplot
    1576         #check if there are any ContourPlot instances
    1577         #in self._objects, and if so change the axes
    1578         #to be frame axes instead of centered axes
    1579         contour = False
    1580         plotfield = False
    1581         matrixplot = False
    1582         from contour_plot import ContourPlot
    1583         from matrix_plot import MatrixPlot
    1584         from plot_field import PlotField
    1585         for g in self.__objects:
    1586             if isinstance(g, ContourPlot):
    1587                 contour = True
    1588             if isinstance(g, PlotField):
    1589                 plotfield = True
    1590             if isinstance(g, MatrixPlot):
    1591                 matrixplot = True
    1592             g._render_on_subplot(subplot)
    1593        
    1594         #adjust the xy limits and draw the axes:
    1595         if axes is None:
    1596             axes = self.__show_axes
    1597 
    1598         #construct an Axes instance, see 'axes.py' for relevant code
    1599         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 code
    1605         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' plot
    1610             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 axes
    1615                 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 grid
    1620                 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 axes
    1626                 # draw the grid
    1627                 sage_gridlines.add_gridlines(subplot, xmin, xmax, ymin, ymax, False)
    1628                 # draw the axes
    1629                 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 axes
    1634                 subplot.set_xlim(xmin, xmax)
    1635                 subplot.set_ylim(ymin, ymax)
    1636                 # draw the grid
    1637                 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 accordingly
    1640             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 grid
    1643             sage_gridlines.add_gridlines(subplot, xmin, xmax, ymin, ymax, True)
    1644             # draw the axes
    1645             if axes: #axes=True unless user specifies axes=False
    1646                 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 accordingly
    1649             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 grid
    1652             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 axes
    1661             if axes: #axes=True unless user specifies axes=False
    1662                 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 most
    1667         # 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 FigureCanvasAgg
    1671             canvas = FigureCanvasAgg(figure)
    16721928            if ext in ['.eps', '.ps', '.pdf']:
    16731929                if dpi is None:
    16741930                    dpi = 72
     
    16801936                    dpi = 100
    16811937            else:
    16821938                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
     1943from matplotlib.ticker import Formatter
     1944
     1945class 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
    16842023
    16852024def xydata_from_point_list(points):
    16862025    r"""
     
    18622201   
    18632202    Some colored functions::
    18642203   
    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')
    18672206   
    18682207    We plot several functions together by passing a list of functions
    18692208    as input::
     
    18852224    The algorithm used to insert extra points is actually pretty
    18862225    simple. On the picture drawn by the lines below::
    18872226   
    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')
    18952234        sage: p.show(axes=False, xmin=-0.5, xmax=1.4, ymin=0, ymax=2)
    18962235   
    18972236    You have the function (in blue) and its approximation (in green)
     
    19192258    We can also directly plot the elliptic curve::
    19202259   
    19212260        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))
    19232262   
    19242263    We can change the line style to one of ``'--'`` (two hyphens, yielding
    19252264    dashed), ``'-.'`` (dash dot), ``'-'`` (solid), ``'steps'``, ``':'`` (dotted)::
     
    21602499    fillcolor = options.pop('fillcolor', 'automatic')
    21612500    fillalpha = options.pop('fillalpha', 0.5)
    21622501
     2502    # TODO: Use matplotlib's fill and fill_between commands.
    21632503    if fill is not None:
    21642504        if parametric or polar:
    21652505            filldata = data
     
    22802620    EXAMPLES: We draw some 2d parametric plots::
    22812621   
    22822622        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) )
    22842624        sage: parametric_plot((1, t), (t, 0, 4))
    22852625
    22862626    Note that in parametric_plot, there is only fill or no fill.
     
    23602700   
    23612701    A green limacon of Pascal::
    23622702   
    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))
    23642704
    23652705    Several polar plots::
    23662706   
     
    24002740    Here are a bunch of random red points::
    24012741   
    24022742        sage: r = [(random(),random()) for _ in range(20)]
    2403         sage: list_plot(r,rgbcolor=(1,0,0))
     2743        sage: list_plot(r,color='red')
    24042744   
    24052745    This gives all the random points joined in a purple line::
    24062746   
    2407         sage: list_plot(r, plotjoined=True, rgbcolor=(1,0,1))
     2747        sage: list_plot(r, plotjoined=True, color='purple')
    24082748
    24092749    If you have separate lists of `x` values and `y` values which you
    24102750    want to plot against each other, use the ``zip`` command to make a
     
    25392879        do_verify = True
    25402880        for i,g in zip(range(1, dims+1), glist):
    25412881            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)
    25462886
    25472887    def save(self, filename=None, dpi=DEFAULT_DPI, figsize=DEFAULT_FIGSIZE,
    25482888             axes = None, **args):
     
    26472987        sage: f(x) = sin(x)
    26482988        sage: g(x) = sin(2*x)
    26492989        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))
    26542994   
    26552995    Now make a graphics array out of the plots; then you can type
    26562996    either: ``ga.show()`` or ``ga.save()``.
  • sage/plot/plot_field.py

    diff -r 22919ed0d91f -r 91a0bec4200a sage/plot/plot_field.py
    a b  
    126126        quiver_options.pop('plot_points')
    127127        subplot.quiver(self.xpos_array, self.ypos_array, self.xvec_array, self.yvec_array, angles='xy', **quiver_options)
    128128 
    129 @options(plot_points=20)
     129@options(plot_points=20,frame=True)
    130130def plot_vector_field((f, g), xrange, yrange, **options):
    131131    r"""
    132132    ``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  
    268268        faceted = options['faceted'] #faceted=True colors the edge of point
    269269        scatteroptions={}
    270270        if not faceted: scatteroptions['edgecolors'] = 'none'
    271 
    272271        subplot.scatter(self.xdata, self.ydata, s=s, c=c, alpha=a, **scatteroptions)
     272       
    273273
    274274def point(points, **kwds):
    275275    """
     
    300300        from sage.plot.plot3d.shapes2 import point3d
    301301        return point3d(points, **kwds)
    302302   
     303@rename_keyword(color='rgbcolor')
    303304@options(alpha=1, pointsize=10, faceted=False, rgbcolor=(0,0,1))
    304305def point2d(points, **options):
    305306    r"""
  • sage/plot/polygon.py

    diff -r 22919ed0d91f -r 91a0bec4200a sage/plot/polygon.py
    a b  
    263263        from sage.plot.plot3d.shapes2 import polygon3d
    264264        return polygon3d(points, **options)
    265265
     266@rename_keyword(color='rgbcolor')
    266267@options(alpha=1, rgbcolor=(0,0,1), thickness=0)
    267268def polygon2d(points, **options):
    268269    r"""
  • sage/plot/text.py

    diff -r 22919ed0d91f -r 91a0bec4200a sage/plot/text.py
    a b  
    168168            opts['transform'] = subplot.transAxes
    169169        subplot.text(self.x, self.y, self.string, **opts)
    170170
    171 
     171@rename_keyword(color='rgbcolor')
    172172@options(fontsize=10, rgbcolor=(0,0,1), horizontal_alignment='center',
    173173         vertical_alignment='center', axis_coords=False)
    174174def text(string, xy, **options):