Exemplo n.º 1
0
  def scatter(self, x, y, s, ax=None, fancy=False, **kwargs):
    """ takes data coordinate x, y and plot them to a data coordinate axes,
        s is the radius in data units. 
        When fancy is True, apply a radient filter so that the 
        edge is blent into the background; better with marker='o' or marker='+'. """
    X, Y, S = numpy.asarray([x, y, s])
    if ax is None: ax=self.default_axes
    
    def filter(image, dpi):
      # this is problematic if the marker is clipped.
      if image.shape[0] <=1 and image.shape[1] <=1: return image
      xgrad = 1.0 \
         - numpy.fabs(numpy.linspace(0, 2, 
            image.shape[0], endpoint=True) - 1.0)
      ygrad = 1.0 \
         - numpy.fabs(numpy.linspace(0, 2, 
            image.shape[1], endpoint=True) - 1.0)
      image[..., 3] *= xgrad[:, None] ** 0.5
      image[..., 3] *= ygrad[None, :] ** 0.5
      return image, 0, 0

    marker = kwargs.pop('marker', 'x')
    verts = kwargs.pop('verts', None)
    # to be API compatible
    if marker is None and not (verts is None):
        marker = (verts, 0)
        verts = None

    objs = []
    color = kwargs.pop('color', None)
    edgecolor = kwargs.pop('edgecolor', None)
    linewidth = kwargs.pop('linewidth', kwargs.pop('lw', None))

    marker_obj = MarkerStyle(marker)
    if not marker_obj.is_filled():
        edgecolor = color

    for x,y,r in numpy.nditer([X, Y, S], flags=['zerosize_ok']):
      path = marker_obj.get_path().transformed(
         marker_obj.get_transform().scale(r).translate(x, y))
      obj = PathPatch(
                path,
                facecolor = color,
                edgecolor = edgecolor,
                linewidth = linewidth,
                transform = ax.transData,
              )
      obj.set_alpha(1.0)
      if fancy:
        obj.set_agg_filter(filter)
        obj.rasterized = True
      objs += [obj]
      ax.add_artist(obj)
    ax.autoscale_view()

    return objs
    def _html_args(self):
        transform = self.line.get_transform() - self.ax.transData
        data = transform.transform(self.line.get_xydata()).tolist()

        markerstyle = MarkerStyle(self.line.get_marker())
        markersize = self.line.get_markersize()
        markerpath = path_data(markerstyle.get_path(),
                               (markerstyle.get_transform()
                                + Affine2D().scale(markersize, -markersize)))

        return dict(lineid=self.lineid,
                    data=json.dumps(data),
                    markerpath=json.dumps(markerpath))
Exemplo n.º 3
0
def get_marker_style(line):
    """Get the style dictionary for matplotlib marker objects"""
    style = {}
    style["alpha"] = line.get_alpha()
    if style["alpha"] is None:
        style["alpha"] = 1

    style["facecolor"] = color_to_hex(line.get_markerfacecolor())
    style["edgecolor"] = color_to_hex(line.get_markeredgecolor())
    style["edgewidth"] = line.get_markeredgewidth()

    style["marker"] = line.get_marker()
    markerstyle = MarkerStyle(line.get_marker())
    markersize = line.get_markersize()
    markertransform = markerstyle.get_transform() + Affine2D().scale(markersize, -markersize)
    style["markerpath"] = SVG_path(markerstyle.get_path(), markertransform)
    style["markersize"] = markersize
    style["zorder"] = line.get_zorder()
    return style
Exemplo n.º 4
0
def get_marker_style(line):
    """Get the style dictionary for matplotlib marker objects"""
    style = {}
    style['alpha'] = line.get_alpha()
    if style['alpha'] is None:
        style['alpha'] = 1

    style['facecolor'] = export_color(line.get_markerfacecolor())
    style['edgecolor'] = export_color(line.get_markeredgecolor())
    style['edgewidth'] = line.get_markeredgewidth()

    style['marker'] = line.get_marker()
    markerstyle = MarkerStyle(line.get_marker())
    markersize = line.get_markersize()
    markertransform = (markerstyle.get_transform()
                       + Affine2D().scale(markersize, -markersize))
    style['markerpath'] = SVG_path(markerstyle.get_path(),
                                   markertransform)
    style['markersize'] = markersize
    style['zorder'] = line.get_zorder()
    return style
Exemplo n.º 5
0
def get_line_style(line):
    """Get the style dictionary for matplotlib Line2D objects."""
    style = {}
    style['alpha'] = line.get_alpha()
    if style['alpha'] is None:
        style['alpha'] = 1
    style['color'] = color_to_hex(line.get_color())
    style['linewidth'] = line.get_linewidth()
    style['dasharray'] = get_dasharray(line)
    style['facecolor'] = color_to_hex(line.get_markerfacecolor())
    style['edgecolor'] = color_to_hex(line.get_markeredgecolor())
    style['edgewidth'] = line.get_markeredgewidth()
    style['marker'] = line.get_marker()
    markerstyle = MarkerStyle(line.get_marker())
    markersize = line.get_markersize()
    markertransform = (markerstyle.get_transform()
                       + Affine2D().scale(markersize, -markersize))
    style['markerpath'] = SVG_path(markerstyle.get_path(), markertransform)
    style['markersize'] = markersize
    style['zorder'] = line.get_zorder()
    return style
Exemplo n.º 6
0
    def update_from(self, other):
        "copy properties from other to self"
        Artist.update_from(self, other)
        self._linestyle = other._linestyle
        self._linewidth = other._linewidth
        self._color = other._color
        self._markersize = other._markersize
        self._markerfacecolor = other._markerfacecolor
        self._markerfacecoloralt = other._markerfacecoloralt
        self._markeredgecolor = other._markeredgecolor
        self._markeredgewidth = other._markeredgewidth
        self._dashSeq = other._dashSeq
        self._dashcapstyle = other._dashcapstyle
        self._dashjoinstyle = other._dashjoinstyle
        self._solidcapstyle = other._solidcapstyle
        self._solidjoinstyle = other._solidjoinstyle

        self._linestyle = other._linestyle
        self._marker = MarkerStyle(other._marker.get_marker(), other._marker.get_fillstyle())
        self._drawstyle = other._drawstyle
Exemplo n.º 7
0
                # Now go through each set of y values
                final_y_values = list()
                final_x_values = list()

                legend_needed = True
                line_label = legend_list[i]

                marker_list = marker_str.split(',')

                if len(marker_list) <= i:
                    final_marker = self.ATTR_MARKER_DEFAULT
                else:
                    final_marker = marker_list[i].strip()

                # check marker
                marker_style = MarkerStyle()
                try:
                    marker_style.set_marker(final_marker)
                except Exception,e:
                    final_marker = ''

                # line width
                line_width_list = line_width_str.split(',')
                if len(line_width_list) > i:
                    final_line_width = line_width_list[i]
                else:
                    final_line_width = '1'

                try:
                    final_line_width = float(final_line_width)
                except Exception, e:
Exemplo n.º 8
0
vectors = pd.read_csv('vectors.csv')

types = vectors['Attribute']
x = vectors['V1']
y = vectors['V2']

fig, ax = plt.subplots()
ax.set_title('2-dimensional metadata embeddings', fontsize=18)
ax.set_xlabel('Feature 1', fontsize=14)
ax.set_ylabel('Feature 2', fontsize=12)
ax.scatter(x,
           y,
           color='r',
           alpha=0.7,
           marker=MarkerStyle(marker='x', fillstyle=None))

for i, txt in enumerate(types):
    ax.annotate(txt, (x[i], y[i]), fontsize=6)

# inset axes....
axins = ax.inset_axes([0.7, 0.6, 0.4, 0.5])
axins.scatter(x, y, color='r', marker=MarkerStyle(marker='x', fillstyle=None))
for i, txt in enumerate(types):
    axins.annotate(txt, (x[i], y[i]), fontsize=8)
# sub region of the original image
x1, x2, y1, y2 = -0.3, -0.1, -0.02, 0.23
axins.set_xlim(x1, x2)
axins.set_ylim(y1, y2)
axins.set_xticklabels('')
axins.set_yticklabels('')
Exemplo n.º 9
0
class Line2D(Artist):
    """
    A line - the line can have both a solid linestyle connecting all
    the vertices, and a marker at each vertex.  Additionally, the
    drawing of the solid line is influenced by the drawstyle, e.g., one
    can create "stepped" lines in various styles.


    """
    lineStyles = _lineStyles = {  # hidden names deprecated
        '-':    '_draw_solid',
        '--':   '_draw_dashed',
        '-.':   '_draw_dash_dot',
        ':':    '_draw_dotted',
        'None': '_draw_nothing',
        ' ':    '_draw_nothing',
        '':     '_draw_nothing',
    }

    _drawStyles_l = {
        'default':    '_draw_lines',
        'steps-mid':  '_draw_steps_mid',
        'steps-pre':  '_draw_steps_pre',
        'steps-post': '_draw_steps_post',
    }

    _drawStyles_s = {
        'steps': '_draw_steps_pre',
    }

    drawStyles = {}
    drawStyles.update(_drawStyles_l)
    drawStyles.update(_drawStyles_s)
    # Need a list ordered with long names first:
    drawStyleKeys = (list(six.iterkeys(_drawStyles_l)) +
                     list(six.iterkeys(_drawStyles_s)))

    # Referenced here to maintain API.  These are defined in
    # MarkerStyle
    markers = MarkerStyle.markers
    filled_markers = MarkerStyle.filled_markers
    fillStyles = MarkerStyle.fillstyles

    zorder = 2
    validCap = ('butt', 'round', 'projecting')
    validJoin = ('miter', 'round', 'bevel')

    def __str__(self):
        if self._label != "":
            return "Line2D(%s)" % (self._label)
        elif self._x is None:
            return "Line2D()"
        elif len(self._x) > 3:
            return "Line2D((%g,%g),(%g,%g),...,(%g,%g))"\
                % (self._x[0], self._y[0], self._x[0],
                   self._y[0], self._x[-1], self._y[-1])
        else:
            return "Line2D(%s)"\
                % (",".join(["(%g,%g)" % (x, y) for x, y
                             in zip(self._x, self._y)]))

    def __init__(self, xdata, ydata,
                 linewidth=None,  # all Nones default to rc
                 linestyle=None,
                 color=None,
                 marker=None,
                 markersize=None,
                 markeredgewidth=None,
                 markeredgecolor=None,
                 markerfacecolor=None,
                 markerfacecoloralt='none',
                 fillstyle=None,
                 antialiased=None,
                 dash_capstyle=None,
                 solid_capstyle=None,
                 dash_joinstyle=None,
                 solid_joinstyle=None,
                 pickradius=5,
                 drawstyle=None,
                 markevery=None,
                 **kwargs
                 ):
        """
        Create a :class:`~matplotlib.lines.Line2D` instance with *x*
        and *y* data in sequences *xdata*, *ydata*.

        The kwargs are :class:`~matplotlib.lines.Line2D` properties:

        %(Line2D)s

        See :meth:`set_linestyle` for a decription of the line styles,
        :meth:`set_marker` for a description of the markers, and
        :meth:`set_drawstyle` for a description of the draw styles.

        """
        Artist.__init__(self)

        #convert sequences to numpy arrays
        if not iterable(xdata):
            raise RuntimeError('xdata must be a sequence')
        if not iterable(ydata):
            raise RuntimeError('ydata must be a sequence')

        if linewidth is None:
            linewidth = rcParams['lines.linewidth']

        if linestyle is None:
            linestyle = rcParams['lines.linestyle']
        if marker is None:
            marker = rcParams['lines.marker']
        if color is None:
            color = rcParams['lines.color']

        if markersize is None:
            markersize = rcParams['lines.markersize']
        if antialiased is None:
            antialiased = rcParams['lines.antialiased']
        if dash_capstyle is None:
            dash_capstyle = rcParams['lines.dash_capstyle']
        if dash_joinstyle is None:
            dash_joinstyle = rcParams['lines.dash_joinstyle']
        if solid_capstyle is None:
            solid_capstyle = rcParams['lines.solid_capstyle']
        if solid_joinstyle is None:
            solid_joinstyle = rcParams['lines.solid_joinstyle']

        if drawstyle is None:
            drawstyle = 'default'

        self._dashcapstyle = None
        self._dashjoinstyle = None
        self._solidjoinstyle = None
        self._solidcapstyle = None
        self.set_dash_capstyle(dash_capstyle)
        self.set_dash_joinstyle(dash_joinstyle)
        self.set_solid_capstyle(solid_capstyle)
        self.set_solid_joinstyle(solid_joinstyle)

        self._linestyles = None
        self._drawstyle = None
        self._linewidth = None

        self._dashSeq = None
        self._dashOffset = 0

        self.set_linestyle(linestyle)
        self.set_drawstyle(drawstyle)
        self.set_linewidth(linewidth)

        self._color = None
        self.set_color(color)
        self._marker = MarkerStyle()
        self.set_marker(marker)

        self._markevery = None
        self._markersize = None
        self._antialiased = None

        self.set_markevery(markevery)
        self.set_antialiased(antialiased)
        self.set_markersize(markersize)

        self._markeredgecolor = None
        self._markeredgewidth = None
        self._markerfacecolor = None
        self._markerfacecoloralt = None

        self.set_markerfacecolor(markerfacecolor)
        self.set_markerfacecoloralt(markerfacecoloralt)
        self.set_markeredgecolor(markeredgecolor)
        self.set_markeredgewidth(markeredgewidth)

        self.set_fillstyle(fillstyle)

        self.verticalOffset = None

        # update kwargs before updating data to give the caller a
        # chance to init axes (and hence unit support)
        self.update(kwargs)
        self.pickradius = pickradius
        self.ind_offset = 0
        if is_numlike(self._picker):
            self.pickradius = self._picker

        self._xorig = np.asarray([])
        self._yorig = np.asarray([])
        self._invalidx = True
        self._invalidy = True
        self._x = None
        self._y = None
        self._xy = None
        self._path = None
        self._transformed_path = None
        self._subslice = False
        self._x_filled = None  # used in subslicing; only x is needed

        self.set_data(xdata, ydata)

    def __getstate__(self):
        state = super(Line2D, self).__getstate__()
        # _linefunc will be restored on draw time.
        state.pop('_lineFunc', None)
        return state

    def contains(self, mouseevent):
        """
        Test whether the mouse event occurred on the line.  The pick
        radius determines the precision of the location test (usually
        within five points of the value).  Use
        :meth:`~matplotlib.lines.Line2D.get_pickradius` or
        :meth:`~matplotlib.lines.Line2D.set_pickradius` to view or
        modify it.

        Returns *True* if any values are within the radius along with
        ``{'ind': pointlist}``, where *pointlist* is the set of points
        within the radius.

        TODO: sort returned indices by distance
        """
        if six.callable(self._contains):
            return self._contains(self, mouseevent)

        if not is_numlike(self.pickradius):
            raise ValueError("pick radius should be a distance")

        # Make sure we have data to plot
        if self._invalidy or self._invalidx:
            self.recache()
        if len(self._xy) == 0:
            return False, {}

        # Convert points to pixels
        transformed_path = self._get_transformed_path()
        path, affine = transformed_path.get_transformed_path_and_affine()
        path = affine.transform_path(path)
        xy = path.vertices
        xt = xy[:, 0]
        yt = xy[:, 1]

        # Convert pick radius from points to pixels
        if self.figure is None:
            warnings.warn('no figure set when check if mouse is on line')
            pixels = self.pickradius
        else:
            pixels = self.figure.dpi / 72. * self.pickradius

        # the math involved in checking for containment (here and inside of
        # segment_hits) assumes that it is OK to overflow.  In case the
        # application has set the error flags such that an exception is raised
        # on overflow, we temporarily set the appropriate error flags here and
        # set them back when we are finished.
        olderrflags = np.seterr(all='ignore')
        try:
            # Check for collision
            if self._linestyle in ['None', None]:
                # If no line, return the nearby point(s)
                d = (xt - mouseevent.x) ** 2 + (yt - mouseevent.y) ** 2
                ind, = np.nonzero(np.less_equal(d, pixels ** 2))
            else:
                # If line, return the nearby segment(s)
                ind = segment_hits(mouseevent.x, mouseevent.y, xt, yt, pixels)
        finally:
            np.seterr(**olderrflags)

        ind += self.ind_offset

        # Debugging message
        if False and self._label != '':
            print("Checking line", self._label,
                  "at", mouseevent.x, mouseevent.y)
            print('xt', xt)
            print('yt', yt)
            #print 'dx,dy', (xt-mouseevent.x)**2., (yt-mouseevent.y)**2.
            print('ind', ind)

        # Return the point(s) within radius
        return len(ind) > 0, dict(ind=ind)

    def get_pickradius(self):
        """return the pick radius used for containment tests"""
        return self.pickradius

    def set_pickradius(self, d):
        """Sets the pick radius used for containment tests

        ACCEPTS: float distance in points
        """
        self.pickradius = d

    def get_fillstyle(self):
        """
        return the marker fillstyle
        """
        return self._marker.get_fillstyle()

    def set_fillstyle(self, fs):
        """
        Set the marker fill style; 'full' means fill the whole marker.
        'none' means no filling; other options are for half-filled markers.

        ACCEPTS: ['full' | 'left' | 'right' | 'bottom' | 'top' | 'none']
        """
        self._marker.set_fillstyle(fs)
        self.stale = True

    def set_markevery(self, every):
        """Set the markevery property to subsample the plot when using markers.

        e.g., if `every=5`, every 5-th marker will be plotted.

        ACCEPTS: [None | int | length-2 tuple of int | slice |
        list/array of int | float | length-2 tuple of float]

        Parameters
        ----------
        every: None | int | length-2 tuple of int | slice | list/array of int |
        float | length-2 tuple of float
            Which markers to plot.

            - every=None, every point will be plotted.
            - every=N, every N-th marker will be plotted starting with
              marker 0.
            - every=(start, N), every N-th marker, starting at point
              start, will be plotted.
            - every=slice(start, end, N), every N-th marker, starting at
              point start, upto but not including point end, will be plotted.
            - every=[i, j, m, n], only markers at points i, j, m, and n
              will be plotted.
            - every=0.1, (i.e. a float) then markers will be spaced at
              approximately equal distances along the line; the distance
              along the line between markers is determined by multiplying the
              display-coordinate distance of the axes bounding-box diagonal
              by the value of every.
            - every=(0.5, 0.1) (i.e. a length-2 tuple of float), the
              same functionality as every=0.1 is exhibited but the first
              marker will be 0.5 multiplied by the
              display-cordinate-diagonal-distance along the line.

        Notes
        -----
        Setting the markevery property will only show markers at actual data
        points.  When using float arguments to set the markevery property
        on irregularly spaced data, the markers will likely not appear evenly
        spaced because the actual data points do not coincide with the
        theoretical spacing between markers.

        When using a start offset to specify the first marker, the offset will
        be from the first data point which may be different from the first
        the visible data point if the plot is zoomed in.

        If zooming in on a plot when using float arguments then the actual
        data points that have markers will change because the distance between
        markers is always determined from the display-coordinates
        axes-bounding-box-diagonal regardless of the actual axes data limits.

        """
        if self._markevery != every:
            self.stale = True
        self._markevery = every

    def get_markevery(self):
        """return the markevery setting"""
        return self._markevery

    def set_picker(self, p):
        """Sets the event picker details for the line.

        ACCEPTS: float distance in points or callable pick function
        ``fn(artist, event)``
        """
        if six.callable(p):
            self._contains = p
        else:
            self.pickradius = p
        self._picker = p

    def get_window_extent(self, renderer):
        bbox = Bbox([[0, 0], [0, 0]])
        trans_data_to_xy = self.get_transform().transform
        bbox.update_from_data_xy(trans_data_to_xy(self.get_xydata()),
                                 ignore=True)
        # correct for marker size, if any
        if self._marker:
            ms = (self._markersize / 72.0 * self.figure.dpi) * 0.5
            bbox = bbox.padded(ms)
        return bbox

    @Artist.axes.setter
    def axes(self, ax):
        # call the set method from the base-class property
        Artist.axes.fset(self, ax)
        if ax is not None:
            # connect unit-related callbacks
            if ax.xaxis is not None:
                self._xcid = ax.xaxis.callbacks.connect('units',
                                                        self.recache_always)
            if ax.yaxis is not None:
                self._ycid = ax.yaxis.callbacks.connect('units',
                                                        self.recache_always)

    def set_data(self, *args):
        """
        Set the x and y data

        ACCEPTS: 2D array (rows are x, y) or two 1D arrays
        """
        if len(args) == 1:
            x, y = args[0]
        else:
            x, y = args

        self.set_xdata(x)
        self.set_ydata(y)

    def recache_always(self):
        self.recache(always=True)

    def recache(self, always=False):
        if always or self._invalidx:
            xconv = self.convert_xunits(self._xorig)
            if ma.isMaskedArray(self._xorig):
                x = ma.asarray(xconv, np.float_).filled(np.nan)
            else:
                x = np.asarray(xconv, np.float_)
            x = x.ravel()
        else:
            x = self._x
        if always or self._invalidy:
            yconv = self.convert_yunits(self._yorig)
            if ma.isMaskedArray(self._yorig):
                y = ma.asarray(yconv, np.float_).filled(np.nan)
            else:
                y = np.asarray(yconv, np.float_)
            y = y.ravel()
        else:
            y = self._y

        if len(x) == 1 and len(y) > 1:
            x = x * np.ones(y.shape, np.float_)
        if len(y) == 1 and len(x) > 1:
            y = y * np.ones(x.shape, np.float_)

        if len(x) != len(y):
            raise RuntimeError('xdata and ydata must be the same length')

        self._xy = np.empty((len(x), 2), dtype=np.float_)
        self._xy[:, 0] = x
        self._xy[:, 1] = y

        self._x = self._xy[:, 0]  # just a view
        self._y = self._xy[:, 1]  # just a view

        self._subslice = False
        if (self.axes and len(x) > 1000 and self._is_sorted(x) and
                self.axes.name == 'rectilinear' and
                self.axes.get_xscale() == 'linear' and
                self._markevery is None and
                self.get_clip_on() is True):
            self._subslice = True
            nanmask = np.isnan(x)
            if nanmask.any():
                self._x_filled = self._x.copy()
                indices = np.arange(len(x))
                self._x_filled[nanmask] = np.interp(indices[nanmask],
                        indices[~nanmask], self._x[~nanmask])
            else:
                self._x_filled = self._x

        if self._path is not None:
            interpolation_steps = self._path._interpolation_steps
        else:
            interpolation_steps = 1
        self._path = Path(self._xy, None, interpolation_steps)
        self._transformed_path = None
        self._invalidx = False
        self._invalidy = False

    def _transform_path(self, subslice=None):
        """
        Puts a TransformedPath instance at self._transformed_path;
        all invalidation of the transform is then handled by the
        TransformedPath instance.
        """
        # Masked arrays are now handled by the Path class itself
        if subslice is not None:
            _steps = self._path._interpolation_steps
            _path = Path(self._xy[subslice, :], _interpolation_steps=_steps)
        else:
            _path = self._path
        self._transformed_path = TransformedPath(_path, self.get_transform())

    def _get_transformed_path(self):
        """
        Return the :class:`~matplotlib.transforms.TransformedPath` instance
        of this line.
        """
        if self._transformed_path is None:
            self._transform_path()
        return self._transformed_path

    def set_transform(self, t):
        """
        set the Transformation instance used by this artist

        ACCEPTS: a :class:`matplotlib.transforms.Transform` instance
        """
        Artist.set_transform(self, t)
        self._invalidx = True
        self._invalidy = True
        self.stale = True

    def _is_sorted(self, x):
        """return True if x is sorted in ascending order"""
        # We don't handle the monotonically decreasing case.
        return _path.is_sorted(x)

    @allow_rasterization
    def draw(self, renderer):
        """draw the Line with `renderer` unless visibility is False"""
        if not self.get_visible():
            return

        if self._invalidy or self._invalidx:
            self.recache()
        self.ind_offset = 0  # Needed for contains() method.
        if self._subslice and self.axes:
            x0, x1 = self.axes.get_xbound()
            i0, = self._x_filled.searchsorted([x0], 'left')
            i1, = self._x_filled.searchsorted([x1], 'right')
            subslice = slice(max(i0 - 1, 0), i1 + 1)
            self.ind_offset = subslice.start
            self._transform_path(subslice)

        transf_path = self._get_transformed_path()

        if self.get_path_effects():
            from matplotlib.patheffects import PathEffectRenderer
            renderer = PathEffectRenderer(self.get_path_effects(), renderer)

        renderer.open_group('line2d', self.get_gid())
        funcname = self._lineStyles.get(self._linestyle, '_draw_nothing')
        if funcname != '_draw_nothing':
            tpath, affine = transf_path.get_transformed_path_and_affine()
            if len(tpath.vertices):
                self._lineFunc = getattr(self, funcname)
                funcname = self.drawStyles.get(self._drawstyle, '_draw_lines')
                drawFunc = getattr(self, funcname)
                gc = renderer.new_gc()
                self._set_gc_clip(gc)

                ln_color_rgba = self._get_rgba_ln_color()
                gc.set_foreground(ln_color_rgba, isRGBA=True)
                gc.set_alpha(ln_color_rgba[3])

                gc.set_antialiased(self._antialiased)
                gc.set_linewidth(self._linewidth)

                if self.is_dashed():
                    cap = self._dashcapstyle
                    join = self._dashjoinstyle
                else:
                    cap = self._solidcapstyle
                    join = self._solidjoinstyle
                gc.set_joinstyle(join)
                gc.set_capstyle(cap)
                gc.set_snap(self.get_snap())
                if self.get_sketch_params() is not None:
                    gc.set_sketch_params(*self.get_sketch_params())

                drawFunc(renderer, gc, tpath, affine.frozen())
                gc.restore()

        if self._marker and self._markersize > 0:
            gc = renderer.new_gc()
            self._set_gc_clip(gc)
            rgbaFace = self._get_rgba_face()
            rgbaFaceAlt = self._get_rgba_face(alt=True)
            edgecolor = self.get_markeredgecolor()
            if is_string_like(edgecolor) and edgecolor.lower() == 'none':
                gc.set_linewidth(0)
                gc.set_foreground(rgbaFace, isRGBA=True)
            else:
                gc.set_foreground(edgecolor)
                gc.set_linewidth(self._markeredgewidth)
                mec = self._markeredgecolor
                if (is_string_like(mec) and mec == 'auto' and
                        rgbaFace is not None):
                    gc.set_alpha(rgbaFace[3])
                else:
                    gc.set_alpha(self.get_alpha())

            marker = self._marker
            tpath, affine = transf_path.get_transformed_points_and_affine()
            if len(tpath.vertices):
                # subsample the markers if markevery is not None
                markevery = self.get_markevery()
                if markevery is not None:
                    subsampled = _mark_every_path(markevery, tpath,
                                                  affine, self.axes.transAxes)
                else:
                    subsampled = tpath

                snap = marker.get_snap_threshold()
                if type(snap) == float:
                    snap = renderer.points_to_pixels(self._markersize) >= snap
                gc.set_snap(snap)
                gc.set_joinstyle(marker.get_joinstyle())
                gc.set_capstyle(marker.get_capstyle())
                marker_path = marker.get_path()
                marker_trans = marker.get_transform()
                w = renderer.points_to_pixels(self._markersize)
                if marker.get_marker() != ',':
                    # Don't scale for pixels, and don't stroke them
                    marker_trans = marker_trans.scale(w)
                else:
                    gc.set_linewidth(0)

                renderer.draw_markers(gc, marker_path, marker_trans,
                                      subsampled, affine.frozen(),
                                      rgbaFace)

                alt_marker_path = marker.get_alt_path()
                if alt_marker_path:
                    alt_marker_trans = marker.get_alt_transform()
                    alt_marker_trans = alt_marker_trans.scale(w)
                    if (is_string_like(mec) and mec == 'auto' and
                            rgbaFaceAlt is not None):
                        gc.set_alpha(rgbaFaceAlt[3])
                    else:
                        gc.set_alpha(self.get_alpha())

                    renderer.draw_markers(
                            gc, alt_marker_path, alt_marker_trans, subsampled,
                            affine.frozen(), rgbaFaceAlt)

            gc.restore()

        renderer.close_group('line2d')
        self.stale = False

    def get_antialiased(self):
        return self._antialiased

    def get_color(self):
        return self._color

    def get_drawstyle(self):
        return self._drawstyle

    def get_linestyle(self):
        return self._linestyle

    def get_linewidth(self):
        return self._linewidth

    def get_marker(self):
        return self._marker.get_marker()

    def get_markeredgecolor(self):
        mec = self._markeredgecolor
        if (is_string_like(mec) and mec == 'auto'):
            if rcParams['_internal.classic_mode']:
                if self._marker.get_marker() in ('.', ','):
                    return self._color
                if self._marker.is_filled() and self.get_fillstyle() != 'none':
                     return 'k'  # Bad hard-wired default...
            return self._color
        else:
            return mec

    def get_markeredgewidth(self):
        return self._markeredgewidth

    def _get_markerfacecolor(self, alt=False):
        if alt:
            fc = self._markerfacecoloralt
        else:
            fc = self._markerfacecolor

        if (is_string_like(fc) and fc.lower() == 'auto'):
            if self.get_fillstyle() == 'none':
                return 'none'
            else:
                return self._color
        else:
            return fc

    def get_markerfacecolor(self):
        return self._get_markerfacecolor(alt=False)

    def get_markerfacecoloralt(self):
        return self._get_markerfacecolor(alt=True)

    def get_markersize(self):
        return self._markersize

    def get_data(self, orig=True):
        """
        Return the xdata, ydata.

        If *orig* is *True*, return the original data.
        """
        return self.get_xdata(orig=orig), self.get_ydata(orig=orig)

    def get_xdata(self, orig=True):
        """
        Return the xdata.

        If *orig* is *True*, return the original data, else the
        processed data.
        """
        if orig:
            return self._xorig
        if self._invalidx:
            self.recache()
        return self._x

    def get_ydata(self, orig=True):
        """
        Return the ydata.

        If *orig* is *True*, return the original data, else the
        processed data.
        """
        if orig:
            return self._yorig
        if self._invalidy:
            self.recache()
        return self._y

    def get_path(self):
        """
        Return the :class:`~matplotlib.path.Path` object associated
        with this line.
        """
        if self._invalidy or self._invalidx:
            self.recache()
        return self._path

    def get_xydata(self):
        """
        Return the *xy* data as a Nx2 numpy array.
        """
        if self._invalidy or self._invalidx:
            self.recache()
        return self._xy

    def set_antialiased(self, b):
        """
        True if line should be drawin with antialiased rendering

        ACCEPTS: [True | False]
        """
        if self._antialiased != b:
            self.stale = True
        self._antialiased = b

    def set_color(self, color):
        """
        Set the color of the line

        ACCEPTS: any matplotlib color
        """
        self._color = color
        self.stale = True

    def set_drawstyle(self, drawstyle):
        """
        Set the drawstyle of the plot

        'default' connects the points with lines. The steps variants
        produce step-plots. 'steps' is equivalent to 'steps-pre' and
        is maintained for backward-compatibility.

        ACCEPTS: ['default' | 'steps' | 'steps-pre' | 'steps-mid' |
                  'steps-post']
        """
        if drawstyle is None:
            drawstyle = 'default'
        if drawstyle not in self.drawStyles:
            raise ValueError('Unrecognized drawstyle ' +
                             ' '.join(self.drawStyleKeys))
        if self._drawstyle != drawstyle:
            self.stale = True
        self._drawstyle = drawstyle

    def set_linewidth(self, w):
        """
        Set the line width in points

        ACCEPTS: float value in points
        """
        w = float(w)
        if self._linewidth != w:
            self.stale = True
        self._linewidth = w

    def set_linestyle(self, ls):
        """
        Set the linestyle of the line (also accepts drawstyles,
        e.g., ``'steps--'``)


        ===========================   =================
        linestyle                     description
        ===========================   =================
        ``'-'`` or ``'solid'``        solid line
        ``'--'`` or  ``'dashed'``     dashed line
        ``'-.'`` or  ``'dashdot'``    dash-dotted line
        ``':'`` or ``'dotted'``       dotted line
        ``'None'``                    draw nothing
        ``' '``                       draw nothing
        ``''``                        draw nothing
        ===========================   =================

        'steps' is equivalent to 'steps-pre' and is maintained for
        backward-compatibility.

        Alternatively a dash tuple of the following form can be provided::

            (offset, onoffseq),

        where ``onoffseq`` is an even length tuple of on and off ink
        in points.


        ACCEPTS: ['solid' | 'dashed', 'dashdot', 'dotted' |
                   (offset, on-off-dash-seq) |
                   ``'-'`` | ``'--'`` | ``'-.'`` | ``':'`` | ``'None'`` |
                   ``' '`` | ``''``]

        .. seealso::

            :meth:`set_drawstyle`
               To set the drawing style (stepping) of the plot.

        Parameters
        ----------
        ls : { '-',  '--', '-.', ':'} and more see description
            The line style.
        """
        if not is_string_like(ls):
            if len(ls) != 2:
                raise ValueError()

            self.set_dashes(ls[1])
            self._dashOffset = ls[0]
            self._linestyle = "--"
            return

        for ds in self.drawStyleKeys:  # long names are first in the list
            if ls.startswith(ds):
                self.set_drawstyle(ds)
                if len(ls) > len(ds):
                    ls = ls[len(ds):]
                else:
                    ls = '-'
                break

        if ls in [' ', '', 'none']:
            ls = 'None'

        if ls not in self._lineStyles:
            try:
                ls = ls_mapper_r[ls]
            except KeyError:
                raise ValueError(("You passed in an invalid linestyle, "
                                  "`{0}`.  See "
                                  "docs of Line2D.set_linestyle for "
                                  "valid values.").format(ls))

        self._linestyle = ls

    @docstring.dedent_interpd
    def set_marker(self, marker):
        """
        Set the line marker

        ACCEPTS: :mod:`A valid marker style <matplotlib.markers>`

        Parameters
        -----------

        marker: marker style
            See `~matplotlib.markers` for full description of possible
            argument

        """
        self._marker.set_marker(marker)
        self.stale = True

    def set_markeredgecolor(self, ec):
        """
        Set the marker edge color

        ACCEPTS: any matplotlib color
        """
        if ec is None:
            ec = 'auto'
        if self._markeredgecolor != ec:
            self.stale = True
        self._markeredgecolor = ec

    def set_markeredgewidth(self, ew):
        """
        Set the marker edge width in points

        ACCEPTS: float value in points
        """
        if ew is None:
            ew = rcParams['lines.markeredgewidth']
        if self._markeredgewidth != ew:
            self.stale = True
        self._markeredgewidth = ew

    def set_markerfacecolor(self, fc):
        """
        Set the marker face color.

        ACCEPTS: any matplotlib color
        """
        if fc is None:
            fc = 'auto'
        if self._markerfacecolor != fc:
            self.stale = True
        self._markerfacecolor = fc

    def set_markerfacecoloralt(self, fc):
        """
        Set the alternate marker face color.

        ACCEPTS: any matplotlib color
        """
        if fc is None:
            fc = 'auto'
        if self._markerfacecoloralt != fc:
            self.stale = True
        self._markerfacecoloralt = fc

    def set_markersize(self, sz):
        """
        Set the marker size in points

        ACCEPTS: float
        """
        sz = float(sz)
        if self._markersize != sz:
            self.stale = True
        self._markersize = sz

    def set_xdata(self, x):
        """
        Set the data np.array for x

        ACCEPTS: 1D array
        """
        self._xorig = x
        self._invalidx = True
        self.stale = True

    def set_ydata(self, y):
        """
        Set the data np.array for y

        ACCEPTS: 1D array
        """
        self._yorig = y
        self._invalidy = True
        self.stale = True

    def set_dashes(self, seq):
        """
        Set the dash sequence, sequence of dashes with on off ink in
        points.  If seq is empty or if seq = (None, None), the
        linestyle will be set to solid.

        ACCEPTS: sequence of on/off ink in points
        """
        if seq == (None, None) or len(seq) == 0:
            self.set_linestyle('-')
        else:
            self.set_linestyle('--')
        if self._dashSeq != seq:
            self.stale = True
        self._dashSeq = seq  # TODO: offset ignored for now

    def _draw_lines(self, renderer, gc, path, trans):
        self._lineFunc(renderer, gc, path, trans)

    def _draw_steps_pre(self, renderer, gc, path, trans):
        steps = np.vstack(pts_to_prestep(*self._xy.T)).T

        path = Path(steps)
        path = path.transformed(self.get_transform())
        self._lineFunc(renderer, gc, path, IdentityTransform())

    def _draw_steps_post(self, renderer, gc, path, trans):
        steps = np.vstack(pts_to_poststep(*self._xy.T)).T

        path = Path(steps)
        path = path.transformed(self.get_transform())
        self._lineFunc(renderer, gc, path, IdentityTransform())

    def _draw_steps_mid(self, renderer, gc, path, trans):
        steps = np.vstack(pts_to_midstep(*self._xy.T)).T

        path = Path(steps)
        path = path.transformed(self.get_transform())
        self._lineFunc(renderer, gc, path, IdentityTransform())

    def _draw_solid(self, renderer, gc, path, trans):
        gc.set_linestyle('solid')
        renderer.draw_path(gc, path, trans)

    def _draw_dashed(self, renderer, gc, path, trans):
        gc.set_linestyle('dashed')
        if self._dashSeq is not None:
            gc.set_dashes(self._dashOffset, self._dashSeq)

        renderer.draw_path(gc, path, trans)

    def _draw_dash_dot(self, renderer, gc, path, trans):
        gc.set_linestyle('dashdot')
        renderer.draw_path(gc, path, trans)

    def _draw_dotted(self, renderer, gc, path, trans):
        gc.set_linestyle('dotted')
        renderer.draw_path(gc, path, trans)

    def update_from(self, other):
        """copy properties from other to self"""
        Artist.update_from(self, other)
        self._linestyle = other._linestyle
        self._linewidth = other._linewidth
        self._color = other._color
        self._markersize = other._markersize
        self._markerfacecolor = other._markerfacecolor
        self._markerfacecoloralt = other._markerfacecoloralt
        self._markeredgecolor = other._markeredgecolor
        self._markeredgewidth = other._markeredgewidth
        self._dashSeq = other._dashSeq
        self._dashOffset = other._dashOffset
        self._dashcapstyle = other._dashcapstyle
        self._dashjoinstyle = other._dashjoinstyle
        self._solidcapstyle = other._solidcapstyle
        self._solidjoinstyle = other._solidjoinstyle

        self._linestyle = other._linestyle
        self._marker = MarkerStyle(other._marker.get_marker(),
                                   other._marker.get_fillstyle())
        self._drawstyle = other._drawstyle

    def _get_rgba_face(self, alt=False):
        facecolor = self._get_markerfacecolor(alt=alt)
        if is_string_like(facecolor) and facecolor.lower() == 'none':
            rgbaFace = None
        else:
            rgbaFace = mcolors.to_rgba(facecolor, self._alpha)
        return rgbaFace

    def _get_rgba_ln_color(self, alt=False):
        return mcolors.to_rgba(self._color, self._alpha)

    # some aliases....
    def set_aa(self, val):
        'alias for set_antialiased'
        self.set_antialiased(val)

    def set_c(self, val):
        'alias for set_color'
        self.set_color(val)

    def set_ls(self, val):
        """alias for set_linestyle"""
        self.set_linestyle(val)

    def set_lw(self, val):
        """alias for set_linewidth"""
        self.set_linewidth(val)

    def set_mec(self, val):
        """alias for set_markeredgecolor"""
        self.set_markeredgecolor(val)

    def set_mew(self, val):
        """alias for set_markeredgewidth"""
        self.set_markeredgewidth(val)

    def set_mfc(self, val):
        """alias for set_markerfacecolor"""
        self.set_markerfacecolor(val)

    def set_mfcalt(self, val):
        """alias for set_markerfacecoloralt"""
        self.set_markerfacecoloralt(val)

    def set_ms(self, val):
        """alias for set_markersize"""
        self.set_markersize(val)

    def get_aa(self):
        """alias for get_antialiased"""
        return self.get_antialiased()

    def get_c(self):
        """alias for get_color"""
        return self.get_color()

    def get_ls(self):
        """alias for get_linestyle"""
        return self.get_linestyle()

    def get_lw(self):
        """alias for get_linewidth"""
        return self.get_linewidth()

    def get_mec(self):
        """alias for get_markeredgecolor"""
        return self.get_markeredgecolor()

    def get_mew(self):
        """alias for get_markeredgewidth"""
        return self.get_markeredgewidth()

    def get_mfc(self):
        """alias for get_markerfacecolor"""
        return self.get_markerfacecolor()

    def get_mfcalt(self, alt=False):
        """alias for get_markerfacecoloralt"""
        return self.get_markerfacecoloralt()

    def get_ms(self):
        """alias for get_markersize"""
        return self.get_markersize()

    def set_dash_joinstyle(self, s):
        """
        Set the join style for dashed linestyles
        ACCEPTS: ['miter' | 'round' | 'bevel']
        """
        s = s.lower()
        if s not in self.validJoin:
            raise ValueError('set_dash_joinstyle passed "%s";\n' % (s,)
                             + 'valid joinstyles are %s' % (self.validJoin,))
        if self._dashjoinstyle != s:
            self.stale = True
        self._dashjoinstyle = s

    def set_solid_joinstyle(self, s):
        """
        Set the join style for solid linestyles
        ACCEPTS: ['miter' | 'round' | 'bevel']
        """
        s = s.lower()
        if s not in self.validJoin:
            raise ValueError('set_solid_joinstyle passed "%s";\n' % (s,)
                             + 'valid joinstyles are %s' % (self.validJoin,))

        if self._solidjoinstyle != s:
            self.stale = True
        self._solidjoinstyle = s

    def get_dash_joinstyle(self):
        """
        Get the join style for dashed linestyles
        """
        return self._dashjoinstyle

    def get_solid_joinstyle(self):
        """
        Get the join style for solid linestyles
        """
        return self._solidjoinstyle

    def set_dash_capstyle(self, s):
        """
        Set the cap style for dashed linestyles

        ACCEPTS: ['butt' | 'round' | 'projecting']
        """
        s = s.lower()
        if s not in self.validCap:
            raise ValueError('set_dash_capstyle passed "%s";\n' % (s,)
                             + 'valid capstyles are %s' % (self.validCap,))
        if self._dashcapstyle != s:
            self.stale = True
        self._dashcapstyle = s

    def set_solid_capstyle(self, s):
        """
        Set the cap style for solid linestyles

        ACCEPTS: ['butt' | 'round' |  'projecting']
        """
        s = s.lower()
        if s not in self.validCap:
            raise ValueError('set_solid_capstyle passed "%s";\n' % (s,)
                             + 'valid capstyles are %s' % (self.validCap,))
        if self._solidcapstyle != s:
            self.stale = True
        self._solidcapstyle = s

    def get_dash_capstyle(self):
        """
        Get the cap style for dashed linestyles
        """
        return self._dashcapstyle

    def get_solid_capstyle(self):
        """
        Get the cap style for solid linestyles
        """
        return self._solidcapstyle

    def is_dashed(self):
        'return True if line is dashstyle'
        return self._linestyle in ('--', '-.', ':')
Exemplo n.º 10
0
def plot_data(path=None,
              measures=None,
              axes=None,
              values=None,
              split_by=None,
              select=None,
              hold=0,
              **kwargs):
    """Create matrix using 'data_to_matrix', then plots in either 2d and 3d."""
    if None in (axes, values):
        raise Exception('plot_data is missing arguments.')

    if len(axes) > 2:
        print(
            'ERROR: plot_data cannot plot more than 2 axes. Taking only first 2 axes.'
        )
        axes = axes[:2]

    if measures is None:
        measures = open_measures(path)
    functions = set([
        v[1].pop('function') for v in values
        if isinstance(v, tuple) and 'function' in v[1]
    ])
    for function in functions:
        newcols = measures.apply(function, axis=1)
        if values is None:
            values = list(newcols)[:1]
        elif not hasattr(values, '__iter__'):
            values = [values]
        #print newcol
        measures = measures.join(newcols)

    values = to_iterable(values)
    if not hasattr(values, '__iter__'):
        values = [values]

    kwargs.setdefault('style', 'scatter')
    idx, mat = data_to_matrix(
        measures=measures,
        axes=axes,
        values=[v[0] if isinstance(v, tuple) else v for v in values],
        split_by=split_by,
        select=select,
        **kwargs)

    dico = kwargs.get('dictionary', {})

    def get_dico(val):
        return dico.get(val, val)

    title = kwargs.pop('title', '')
    if not split_by is None:
        newfig = kwargs.pop('newfig', 1)
        for ik, key in enumerate(sorted(idx)):
            kw = {}
            kw.update(kwargs)
            kw['newfig'] = newfig
            kw.setdefault('color', get_cmap(ik, len(idx)))
            from matplotlib.markers import MarkerStyle
            from itertools import product as iprod
            markers = sorted(list(
                iprod(['o', 'X', '^', 's', 'p', 'v', 'P'][:(len(idx) + 1) / 2],
                      ('full', 'none'))),
                             key=lambda e: e[1],
                             reverse=1) * 50
            kw.setdefault(
                'marker',
                MarkerStyle(marker=markers[ik][0], fillstyle=markers[ik][1]))
            make_figure(idx[key],
                        mat[key],
                        title=title,
                        axes=axes,
                        values=values,
                        **kw)
            newfig = False
        if kwargs.get('show_legends', True):
            plt.legend([
                ', '.join([
                    r'{}={}'.format(get_dico(j[0]), get_dico(j[1]))
                    if get_dico(j[0]) else r'{}'.format(get_dico(j[1]))
                    for j in i
                ]) for i in sorted(idx)
            ])
    else:
        #print split_by, mat.keys()
        make_figure(idx, mat, axes=axes, values=values, title=title, **kwargs)

    if not hold:
        plt.show()
Exemplo n.º 11
0
    def Draw(self, products, micapsfile, debug=True):
        """
        根据产品参数绘制图像
        :param micapsfile: 指定绘制产品中包含的一个micapsfile
        :param debug: 调试状态
        :param products: 产品参数 
        :return: 
        """
        self.UpdateData(products, micapsfile)
        extents = products.picture.extents
        xmax = extents.xmax
        xmin = extents.xmin
        ymax = extents.ymax
        ymin = extents.ymin

        # 设置绘图画板的宽和高 单位:英寸
        h = products.picture.height
        if products.map.projection.name == 'sall':  # 等经纬度投影时不用配置本身的宽度,直接根据宽高比得到
            w = h * np.math.fabs(
                (xmax - xmin) / (ymax - ymin)) * products.picture.widthshrink
        else:
            w = products.picture.width

        # 创建画布
        fig = plt.figure(figsize=(w, h),
                         dpi=products.picture.dpi,
                         facecolor="white")  # 必须在前面
        ax = fig.add_subplot(111)
        ax.spines['bottom'].set_linewidth(products.map.projection.axisthick)
        ax.spines['left'].set_linewidth(products.map.projection.axisthick)
        ax.spines['right'].set_linewidth(products.map.projection.axisthick)
        ax.spines['top'].set_linewidth(products.map.projection.axisthick)
        # 设置绘图区域
        plt.xlim(xmin, xmax)
        plt.ylim(ymin, ymax)

        # 背景透明
        fig.patch.set_alpha(products.picture.opacity)

        # 坐标系统尽可能靠近绘图区边界
        fig.tight_layout(pad=products.picture.pad)

        clipborder = products.map.clipborders[0]

        # 获得产品投影
        from Projection import Projection
        m = Projection.GetProjection(products)

        if m is not plt:
            # 用投影更新经纬度数据
            self.X, self.Y = Micaps.UpdateXY(m, self.X, self.Y)
            # 用投影更新产品参数中涉及经纬度的数据
            Micaps.Update(products, m)
            # 画世界底图
            Map.DrawWorld(products, m)

        # 绘制裁切区域边界
        patch = Map.DrawClipBorders(products.map.clipborders)

        # draw parallels and meridians.
        Map.DrawGridLine(products, m)

        cmap = nclcmaps.cmaps(
            micapsfile.legend.micapslegendcolor)  # cm.jet  temp_diff_18lev
        vmax = math.ceil(self.max)
        vmin = math.floor(self.min)
        levels = arange(vmin - self.distance, vmax + self.distance + 0.1,
                        self.distance)

        if micapsfile.legend.micapslegendvalue:
            level = levels
        else:
            level = micapsfile.legend.legendvalue

        # 绘制等值线 ------ 等值线和标注是一体的
        c = micapsfile.contour

        Map.DrawContourAndMark(contour=c,
                               x=self.X,
                               y=self.Y,
                               z=self.Z,
                               level=level,
                               clipborder=clipborder,
                               patch=patch,
                               m=m)

        cf = micapsfile.contour
        cbar = micapsfile.legend
        extend = micapsfile.legend.extend
        # 绘制色斑图 ------ 色版图、图例、裁切是一体的
        Map.DrawContourfAndLegend(contourf=cf,
                                  legend=cbar,
                                  clipborder=clipborder,
                                  patch=patch,
                                  cmap=cmap,
                                  levels=levels,
                                  extend=extend,
                                  extents=extents,
                                  x=self.X,
                                  y=self.Y,
                                  z=self.Z,
                                  m=m)

        # 绘制描述文本
        MicapsFile.MicapsFile.DrawTitle(m, micapsfile.title, self.title)

        self.DrawUV(m, micapsfile, clipborder, patch)

        # 绘制地图
        Map.DrawBorders(m, products)

        # 绘制散点
        if micapsfile.contour.scatter:
            if hasattr(self, 'x1'):
                m.scatter(self.x1,
                          self.y1,
                          s=micapsfile.contour.radius,
                          c=self.z1,
                          alpha=micapsfile.contour.alpha,
                          edgecolors='b')
            else:
                m.scatter(self.X,
                          self.Y,
                          s=micapsfile.contour.radius,
                          c=self.Z,
                          alpha=micapsfile.contour.alpha,
                          edgecolors='b')

        # 绘制站点
        stations = products.map.stations
        if stations.visible:
            # 'code': code, 'lon': lon, 'lat': lat, 'height': height,
            # 'iclass': iclass, 'infosum': infosum, 'name': info[0]
            # stations_tuple = tuple(stations.micapsdata.stations)
            # (code, lat, lon, height, iclass, infosum, info[0])
            # stations_array = np.array(stations.micapsdata.stations, dtype=[
            #     ('code', 'U'),
            #     ('lat', np.float32),
            #     ('lon', np.float32),
            #     ('height', np.float32),
            #     ('iclass', 'i'),
            #     ('infosum', 'i'),
            #     ('info', 'U')
            # ])

            # stations_array = [list(ele) for ele in zip(*stations.micapsdata.stations)]
            stations_array = zip(*stations.micapsdata.stations)
            # 画站点mark
            if m is not plt:
                stations_array[2], stations_array[1] = \
                    Micaps.UpdateXY(m, stations_array[2], stations_array[1])
            marker = MarkerStyle(stations.markstyle[0], stations.markstyle[1])
            m.scatter(stations_array[2],
                      stations_array[1],
                      marker=marker,
                      s=stations.radius,
                      c=stations.color,
                      alpha=stations.alpha,
                      edgecolors=stations.edgecolors)

            # 画站点文本

            fontfile = r"C:\WINDOWS\Fonts\{0}".format(stations.font[1])
            if not os.path.exists(fontfile):
                font = FontProperties(size=stations.font[0],
                                      weight=stations.font[2])
            else:
                font = FontProperties(fname=fontfile,
                                      size=stations.font[0],
                                      weight=stations.font[2])
            for sta in stations.micapsdata.stations:
                if m is not plt:
                    lon, lat = Micaps.UpdateXY(m, sta[2], sta[1])
                    lon1, lat1 = Micaps.UpdateXY(m, sta[2] + stations.detax,
                                                 sta[1])
                    deta = lon1 - lon
                else:
                    lon, lat = sta[2], sta[1]
                    deta = stations.detax
                plt.text(lon + deta,
                         lat,
                         sta[6],
                         fontproperties=font,
                         rotation=0,
                         color=stations.font[3],
                         ha='left',
                         va='center')

        # 接近收尾

        # self.Clip(clipborder, fig, patch)

        # 存图
        Picture.savePicture(fig, products.picture.picfile)

        print(products.picture.picfile + u'存图成功!')
        if debug:
            plt.show()
list1_2 = [p_mid_BE[0], p_mid_EC[0]]
list2_2 = [p_mid_BE[1], p_mid_EC[1]]

#T# plot the figure
ax1.plot(list1, list2, 'k')

#T# plot the points
ax1.scatter(list1, list2, s=12, color='k')

#T# set the math text font to the Latex default, Computer Modern
import matplotlib
matplotlib.rcParams['mathtext.fontset'] = 'cm'

#T# create the markers
marker1 = MarkerStyle(r'$|$')
marker1._transform.scale(1.6, 2.2)
marker1._transform.rotate_deg(63)

marker2 = MarkerStyle(r'$||$')
marker2._transform.scale(1.6, 2.2)
marker2._transform.rotate_deg(-48)

#T# plot the markers
ax1.plot(list1_1, list2_1, 'k', marker=marker1)
ax1.plot(list1_2, list2_2, 'k', marker=marker2)

#T# create the labels
label_A = ax1.annotate(r'$A$', (A[0], A[1]), ha='right', va='top', size=18)
label_B = ax1.annotate(r'$B$', (B[0], B[1]), ha='left', va='top', size=18)
label_C = ax1.annotate(r'$C$', (C[0], C[1]), ha='center', va='bottom', size=18)
Exemplo n.º 13
0
#T# plot the figure
ax1.plot(list_x_1a, list_y_1a, 'k')
ax1.plot(list_x_1b, list_y_1b, 'k')
ax1.plot(list_x_1c, list_y_1c, 'k')
ax1.scatter(list_x_2, list_y_2, s = 12, color = 'k')

arc1 = mpatches.Arc(B, 1, 1, theta2 = math.degrees(a_ABC))
ax1.add_patch(arc1)

#T# set the math text font to the Latex default, Computer Modern
import matplotlib
matplotlib.rcParams['mathtext.fontset'] = 'cm'

#T# create the markers
marker1 = MarkerStyle(r'|')
marker1._transform.scale(1, 2)
marker1._transform.rotate(math.pi/2 + a_marker1)

marker2 = MarkerStyle(r'|')
marker2._transform.scale(1, 2)
marker2._transform.rotate(math.pi/2 + a_marker2)

#T# plot the markers
ax1.plot(p_marker1[0], p_marker1[1], 'k', marker = marker1)
ax1.plot(p_marker2[0], p_marker2[1], 'k', marker = marker2)

#T# create the labels
label_A = ax1.annotate(r'$A$', A, ha = 'right', va = 'bottom', size = 16)
label_B = ax1.annotate(r'$B$', B, ha = 'right', va = 'top', size = 16)
label_C = ax1.annotate(r'$C$', C, ha = 'left', va = 'top', size = 16)
Exemplo n.º 14
0
def draw_pathcollection(data, obj):
    """Returns PGFPlots code for a number of patch objects.
    """
    content = []
    # gather data
    assert obj.get_offsets() is not None
    labels = ["x" + 21 * " ", "y" + 21 * " "]
    dd = obj.get_offsets()

    draw_options = ["only marks"]
    table_options = []

    if obj.get_array() is not None:
        draw_options.append("scatter")
        dd = numpy.column_stack([dd, obj.get_array()])
        labels.append("colordata" + 13 * " ")
        draw_options.append("scatter src=explicit")
        table_options.extend(["x=x", "y=y", "meta=colordata"])
        ec = None
        fc = None
        ls = None
        marker0 = None
    else:
        # gather the draw options
        try:
            ec = obj.get_edgecolors()[0]
        except (TypeError, IndexError):
            ec = None

        try:
            fc = obj.get_facecolors()[0]
        except (TypeError, IndexError):
            fc = None

        try:
            ls = obj.get_linestyle()[0]
        except (TypeError, IndexError):
            ls = None

        # "solution" from
        # <https://github.com/matplotlib/matplotlib/issues/4672#issuecomment-378702670>
        p = obj.get_paths()[0]
        ms = {style: MarkerStyle(style) for style in MarkerStyle.markers}
        paths = {
            style: marker.get_path().transformed(marker.get_transform())
            for style, marker in ms.items()
        }
        marker0 = None
        for marker, path in paths.items():
            if (numpy.all(path.codes == p.codes)
                    and (path.vertices.shape == p.vertices.shape)
                    and numpy.max(
                        numpy.abs(path.vertices - p.vertices)) < 1.0e-10):
                marker0 = marker
                break

    is_contour = len(dd) == 1
    if is_contour:
        draw_options = ["draw=none"]

    if marker0 is not None:
        data, pgfplots_marker, marker_options = _mpl_marker2pgfp_marker(
            data, marker0, fc)
        draw_options += ["marker={}".format(pgfplots_marker)] + marker_options

    # `only mark` plots don't need linewidth
    data, extra_draw_options = get_draw_options(data, obj, ec, fc, ls, None)
    draw_options += extra_draw_options

    if obj.get_cmap():
        mycolormap, is_custom_cmap = _mpl_cmap2pgf_cmap(obj.get_cmap(), data)
        draw_options.append("colormap" + ("=" if is_custom_cmap else "/") +
                            mycolormap)

    legend_text = get_legend_text(obj)
    if legend_text is None and has_legend(obj.axes):
        draw_options.append("forget plot")

    for path in obj.get_paths():
        if is_contour:
            dd = path.vertices

        if len(obj.get_sizes()) == len(dd):
            # See Pgfplots manual, chapter 4.25.
            # In Pgfplots, \mark size specifies raddi, in matplotlib circle areas.
            radii = numpy.sqrt(obj.get_sizes() / numpy.pi)
            dd = numpy.column_stack([dd, radii])
            labels.append("sizedata" + 14 * " ")
            draw_options.extend([
                "visualization depends on="
                "{\\thisrow{sizedata} \\as\\perpointmarksize}",
                "scatter/@pre marker code/.append style="
                "{/tikz/mark size=\\perpointmarksize}",
            ])

        do = " [{}]".format(", ".join(draw_options)) if draw_options else ""
        content.append("\\addplot{}\n".format(do))

        to = " [{}]".format(", ".join(table_options)) if table_options else ""
        content.append("table{}{{%\n".format(to))

        content.append((" ".join(labels)).strip() + "\n")
        ff = data["float format"]
        fmt = (" ".join(dd.shape[1] * [ff])) + "\n"
        for d in dd:
            content.append(fmt.format(*tuple(d)))
        content.append("};\n")

    if legend_text is not None:
        content.append("\\addlegendentry{{{}}}\n".format(legend_text))

    return data, content
Exemplo n.º 15
0
class Line2D(Artist):
    """
    A line - the line can have both a solid linestyle connecting all
    the vertices, and a marker at each vertex.  Additionally, the
    drawing of the solid line is influenced by the drawstyle, e.g., one
    can create "stepped" lines in various styles.


    """
    lineStyles = _lineStyles = {  # hidden names deprecated
        '-':    '_draw_solid',
        '--':   '_draw_dashed',
        '-.':   '_draw_dash_dot',
        ':':    '_draw_dotted',
        'None': '_draw_nothing',
        ' ':    '_draw_nothing',
        '':     '_draw_nothing',
    }

    _drawStyles_l = {
        'default': '_draw_lines',
        'steps-mid': '_draw_steps_mid',
        'steps-pre': '_draw_steps_pre',
        'steps-post': '_draw_steps_post',
    }

    _drawStyles_s = {
        'steps': '_draw_steps_pre',
    }

    drawStyles = {}
    drawStyles.update(_drawStyles_l)
    drawStyles.update(_drawStyles_s)
    # Need a list ordered with long names first:
    drawStyleKeys = (list(six.iterkeys(_drawStyles_l)) +
                     list(six.iterkeys(_drawStyles_s)))

    # Referenced here to maintain API.  These are defined in
    # MarkerStyle
    markers = MarkerStyle.markers
    filled_markers = MarkerStyle.filled_markers
    fillStyles = MarkerStyle.fillstyles

    zorder = 2
    validCap = ('butt', 'round', 'projecting')
    validJoin = ('miter', 'round', 'bevel')

    def __str__(self):
        if self._label != "":
            return "Line2D(%s)" % (self._label)
        elif hasattr(self, '_x') and len(self._x) > 3:
            return "Line2D((%g,%g),(%g,%g),...,(%g,%g))"\
                % (self._x[0], self._y[0], self._x[0],
                   self._y[0], self._x[-1], self._y[-1])
        elif hasattr(self, '_x'):
            return "Line2D(%s)"\
                % (",".join(["(%g,%g)" % (x, y) for x, y
                             in zip(self._x, self._y)]))
        else:
            return "Line2D()"

    def __init__(
            self,
            xdata,
            ydata,
            linewidth=None,  # all Nones default to rc
            linestyle=None,
            color=None,
            marker=None,
            markersize=None,
            markeredgewidth=None,
            markeredgecolor=None,
            markerfacecolor=None,
            markerfacecoloralt='none',
            fillstyle='full',
            antialiased=None,
            dash_capstyle=None,
            solid_capstyle=None,
            dash_joinstyle=None,
            solid_joinstyle=None,
            pickradius=5,
            drawstyle=None,
            markevery=None,
            **kwargs):
        """
        Create a :class:`~matplotlib.lines.Line2D` instance with *x*
        and *y* data in sequences *xdata*, *ydata*.

        The kwargs are :class:`~matplotlib.lines.Line2D` properties:

        %(Line2D)s

        See :meth:`set_linestyle` for a decription of the line styles,
        :meth:`set_marker` for a description of the markers, and
        :meth:`set_drawstyle` for a description of the draw styles.

        """
        Artist.__init__(self)

        #convert sequences to numpy arrays
        if not iterable(xdata):
            raise RuntimeError('xdata must be a sequence')
        if not iterable(ydata):
            raise RuntimeError('ydata must be a sequence')

        if linewidth is None:
            linewidth = rcParams['lines.linewidth']

        if linestyle is None:
            linestyle = rcParams['lines.linestyle']
        if marker is None:
            marker = rcParams['lines.marker']
        if color is None:
            color = rcParams['lines.color']

        if markersize is None:
            markersize = rcParams['lines.markersize']
        if antialiased is None:
            antialiased = rcParams['lines.antialiased']
        if dash_capstyle is None:
            dash_capstyle = rcParams['lines.dash_capstyle']
        if dash_joinstyle is None:
            dash_joinstyle = rcParams['lines.dash_joinstyle']
        if solid_capstyle is None:
            solid_capstyle = rcParams['lines.solid_capstyle']
        if solid_joinstyle is None:
            solid_joinstyle = rcParams['lines.solid_joinstyle']

        if drawstyle is None:
            drawstyle = 'default'

        self.set_dash_capstyle(dash_capstyle)
        self.set_dash_joinstyle(dash_joinstyle)
        self.set_solid_capstyle(solid_capstyle)
        self.set_solid_joinstyle(solid_joinstyle)

        self.set_linestyle(linestyle)
        self.set_drawstyle(drawstyle)
        self.set_linewidth(linewidth)
        self.set_color(color)
        self._marker = MarkerStyle()
        self.set_marker(marker)
        self.set_markevery(markevery)
        self.set_antialiased(antialiased)
        self.set_markersize(markersize)
        self._dashSeq = None

        self.set_markerfacecolor(markerfacecolor)
        self.set_markerfacecoloralt(markerfacecoloralt)
        self.set_markeredgecolor(markeredgecolor)
        self.set_markeredgewidth(markeredgewidth)
        self.set_fillstyle(fillstyle)

        self.verticalOffset = None

        # update kwargs before updating data to give the caller a
        # chance to init axes (and hence unit support)
        self.update(kwargs)
        self.pickradius = pickradius
        self.ind_offset = 0
        if is_numlike(self._picker):
            self.pickradius = self._picker

        self._xorig = np.asarray([])
        self._yorig = np.asarray([])
        self._invalidx = True
        self._invalidy = True
        self.set_data(xdata, ydata)

    def __getstate__(self):
        state = super(Line2D, self).__getstate__()
        # _linefunc will be restored on draw time.
        state.pop('_lineFunc', None)
        return state

    def contains(self, mouseevent):
        """
        Test whether the mouse event occurred on the line.  The pick
        radius determines the precision of the location test (usually
        within five points of the value).  Use
        :meth:`~matplotlib.lines.Line2D.get_pickradius` or
        :meth:`~matplotlib.lines.Line2D.set_pickradius` to view or
        modify it.

        Returns *True* if any values are within the radius along with
        ``{'ind': pointlist}``, where *pointlist* is the set of points
        within the radius.

        TODO: sort returned indices by distance
        """
        if six.callable(self._contains):
            return self._contains(self, mouseevent)

        if not is_numlike(self.pickradius):
            raise ValueError("pick radius should be a distance")

        # Make sure we have data to plot
        if self._invalidy or self._invalidx:
            self.recache()
        if len(self._xy) == 0:
            return False, {}

        # Convert points to pixels
        transformed_path = self._get_transformed_path()
        path, affine = transformed_path.get_transformed_path_and_affine()
        path = affine.transform_path(path)
        xy = path.vertices
        xt = xy[:, 0]
        yt = xy[:, 1]

        # Convert pick radius from points to pixels
        if self.figure is None:
            warnings.warn('no figure set when check if mouse is on line')
            pixels = self.pickradius
        else:
            pixels = self.figure.dpi / 72. * self.pickradius

        # the math involved in checking for containment (here and inside of
        # segment_hits) assumes that it is OK to overflow.  In case the
        # application has set the error flags such that an exception is raised
        # on overflow, we temporarily set the appropriate error flags here and
        # set them back when we are finished.
        olderrflags = np.seterr(all='ignore')
        try:
            # Check for collision
            if self._linestyle in ['None', None]:
                # If no line, return the nearby point(s)
                d = (xt - mouseevent.x)**2 + (yt - mouseevent.y)**2
                ind, = np.nonzero(np.less_equal(d, pixels**2))
            else:
                # If line, return the nearby segment(s)
                ind = segment_hits(mouseevent.x, mouseevent.y, xt, yt, pixels)
        finally:
            np.seterr(**olderrflags)

        ind += self.ind_offset

        # Debugging message
        if False and self._label != '':
            print("Checking line", self._label, "at", mouseevent.x,
                  mouseevent.y)
            print('xt', xt)
            print('yt', yt)
            #print 'dx,dy', (xt-mouseevent.x)**2., (yt-mouseevent.y)**2.
            print('ind', ind)

        # Return the point(s) within radius
        return len(ind) > 0, dict(ind=ind)

    def get_pickradius(self):
        """return the pick radius used for containment tests"""
        return self.pickradius

    def set_pickradius(self, d):
        """Sets the pick radius used for containment tests

        ACCEPTS: float distance in points
        """
        self.pickradius = d

    def get_fillstyle(self):
        """
        return the marker fillstyle
        """
        return self._marker.get_fillstyle()

    def set_fillstyle(self, fs):
        """
        Set the marker fill style; 'full' means fill the whole marker.
        'none' means no filling; other options are for half-filled markers.

        ACCEPTS: ['full' | 'left' | 'right' | 'bottom' | 'top' | 'none']
        """
        self._marker.set_fillstyle(fs)

    def set_markevery(self, every):
        """Set the markevery property to subsample the plot when using markers.

        e.g., if `every=5`, every 5-th marker will be plotted.

        ACCEPTS: [None | int | length-2 tuple of int | slice |
        list/array of int | float | length-2 tuple of float]

        Parameters
        ----------
        every: None | int | length-2 tuple of int | slice | list/array of int |
        float | length-2 tuple of float
            Which markers to plot.

            - every=None, every point will be plotted.
            - every=N, every N-th marker will be plotted starting with
              marker 0.
            - every=(start, N), every N-th marker, starting at point
              start, will be plotted.
            - every=slice(start, end, N), every N-th marker, starting at
              point start, upto but not including point end, will be plotted.
            - every=[i, j, m, n], only markers at points i, j, m, and n
              will be plotted.
            - every=0.1, (i.e. a float) then markers will be spaced at
              approximately equal distances along the line; the distance
              along the line between markers is determined by multiplying the
              display-coordinate distance of the axes bounding-box diagonal
              by the value of every.
            - every=(0.5, 0.1) (i.e. a length-2 tuple of float), the
              same functionality as every=0.1 is exhibited but the first
              marker will be 0.5 multiplied by the
              display-cordinate-diagonal-distance along the line.

        Notes
        -----
        Setting the markevery property will only show markers at actual data
        points.  When using float arguments to set the markevery property
        on irregularly spaced data, the markers will likely not appear evenly
        spaced because the actual data points do not coincide with the
        theoretical spacing between markers.

        When using a start offset to specify the first marker, the offset will
        be from the first data point which may be different from the first
        the visible data point if the plot is zoomed in.

        If zooming in on a plot when using float arguments then the actual
        data points that have markers will change because the distance between
        markers is always determined from the display-coordinates
        axes-bounding-box-diagonal regardless of the actual axes data limits.

        """

        self._markevery = every

    def get_markevery(self):
        """return the markevery setting"""
        return self._markevery

    def set_picker(self, p):
        """Sets the event picker details for the line.

        ACCEPTS: float distance in points or callable pick function
        ``fn(artist, event)``
        """
        if six.callable(p):
            self._contains = p
        else:
            self.pickradius = p
        self._picker = p

    def get_window_extent(self, renderer):
        bbox = Bbox([[0, 0], [0, 0]])
        trans_data_to_xy = self.get_transform().transform
        bbox.update_from_data_xy(trans_data_to_xy(self.get_xydata()),
                                 ignore=True)
        # correct for marker size, if any
        if self._marker:
            ms = (self._markersize / 72.0 * self.figure.dpi) * 0.5
            bbox = bbox.padded(ms)
        return bbox

    @Artist.axes.setter
    def axes(self, ax):
        # call the set method from the base-class property
        Artist.axes.fset(self, ax)
        # connect unit-related callbacks
        if ax.xaxis is not None:
            self._xcid = ax.xaxis.callbacks.connect('units',
                                                    self.recache_always)
        if ax.yaxis is not None:
            self._ycid = ax.yaxis.callbacks.connect('units',
                                                    self.recache_always)

    def set_data(self, *args):
        """
        Set the x and y data

        ACCEPTS: 2D array (rows are x, y) or two 1D arrays
        """
        if len(args) == 1:
            x, y = args[0]
        else:
            x, y = args

        self.set_xdata(x)
        self.set_ydata(y)

    def recache_always(self):
        self.recache(always=True)

    def recache(self, always=False):
        if always or self._invalidx:
            xconv = self.convert_xunits(self._xorig)
            if ma.isMaskedArray(self._xorig):
                x = ma.asarray(xconv, np.float_)
            else:
                x = np.asarray(xconv, np.float_)
            x = x.ravel()
        else:
            x = self._x
        if always or self._invalidy:
            yconv = self.convert_yunits(self._yorig)
            if ma.isMaskedArray(self._yorig):
                y = ma.asarray(yconv, np.float_)
            else:
                y = np.asarray(yconv, np.float_)
            y = y.ravel()
        else:
            y = self._y

        if len(x) == 1 and len(y) > 1:
            x = x * np.ones(y.shape, np.float_)
        if len(y) == 1 and len(x) > 1:
            y = y * np.ones(x.shape, np.float_)

        if len(x) != len(y):
            raise RuntimeError('xdata and ydata must be the same length')

        x = x.reshape((len(x), 1))
        y = y.reshape((len(y), 1))

        if ma.isMaskedArray(x) or ma.isMaskedArray(y):
            self._xy = ma.concatenate((x, y), 1)
        else:
            self._xy = np.concatenate((x, y), 1)
        self._x = self._xy[:, 0]  # just a view
        self._y = self._xy[:, 1]  # just a view

        self._subslice = False
        if (self.axes and len(x) > 100 and self._is_sorted(x)
                and self.axes.name == 'rectilinear'
                and self.axes.get_xscale() == 'linear'
                and self._markevery is None and self.get_clip_on() is True):
            self._subslice = True
        if hasattr(self, '_path'):
            interpolation_steps = self._path._interpolation_steps
        else:
            interpolation_steps = 1
        self._path = Path(self._xy, None, interpolation_steps)
        self._transformed_path = None
        self._invalidx = False
        self._invalidy = False

    def _transform_path(self, subslice=None):
        """
        Puts a TransformedPath instance at self._transformed_path,
        all invalidation of the transform is then handled by the
        TransformedPath instance.
        """
        # Masked arrays are now handled by the Path class itself
        if subslice is not None:
            _path = Path(self._xy[subslice, :])
        else:
            _path = self._path
        self._transformed_path = TransformedPath(_path, self.get_transform())

    def _get_transformed_path(self):
        """
        Return the :class:`~matplotlib.transforms.TransformedPath` instance
        of this line.
        """
        if self._transformed_path is None:
            self._transform_path()
        return self._transformed_path

    def set_transform(self, t):
        """
        set the Transformation instance used by this artist

        ACCEPTS: a :class:`matplotlib.transforms.Transform` instance
        """
        Artist.set_transform(self, t)
        self._invalidx = True
        self._invalidy = True

    def _is_sorted(self, x):
        """return true if x is sorted"""
        if len(x) < 2:
            return 1
        return np.amin(x[1:] - x[0:-1]) >= 0

    @allow_rasterization
    def draw(self, renderer):
        """draw the Line with `renderer` unless visibility is False"""
        if not self.get_visible():
            return

        if self._invalidy or self._invalidx:
            self.recache()
        self.ind_offset = 0  # Needed for contains() method.
        if self._subslice and self.axes:
            # Need to handle monotonically decreasing case also...
            x0, x1 = self.axes.get_xbound()
            i0, = self._x.searchsorted([x0], 'left')
            i1, = self._x.searchsorted([x1], 'right')
            subslice = slice(max(i0 - 1, 0), i1 + 1)
            self.ind_offset = subslice.start
            self._transform_path(subslice)

        transf_path = self._get_transformed_path()

        if self.get_path_effects():
            from matplotlib.patheffects import PathEffectRenderer
            renderer = PathEffectRenderer(self.get_path_effects(), renderer)

        renderer.open_group('line2d', self.get_gid())
        gc = renderer.new_gc()
        self._set_gc_clip(gc)

        ln_color_rgba = self._get_rgba_ln_color()
        gc.set_foreground(ln_color_rgba, isRGBA=True)
        gc.set_alpha(ln_color_rgba[3])

        gc.set_antialiased(self._antialiased)
        gc.set_linewidth(self._linewidth)

        if self.is_dashed():
            cap = self._dashcapstyle
            join = self._dashjoinstyle
        else:
            cap = self._solidcapstyle
            join = self._solidjoinstyle
        gc.set_joinstyle(join)
        gc.set_capstyle(cap)
        gc.set_snap(self.get_snap())
        if self.get_sketch_params() is not None:
            gc.set_sketch_params(*self.get_sketch_params())

        funcname = self._lineStyles.get(self._linestyle, '_draw_nothing')
        if funcname != '_draw_nothing':
            tpath, affine = transf_path.get_transformed_path_and_affine()
            if len(tpath.vertices):
                self._lineFunc = getattr(self, funcname)
                funcname = self.drawStyles.get(self._drawstyle, '_draw_lines')
                drawFunc = getattr(self, funcname)
                drawFunc(renderer, gc, tpath, affine.frozen())

        if self._marker:
            gc = renderer.new_gc()
            self._set_gc_clip(gc)
            rgbaFace = self._get_rgba_face()
            rgbaFaceAlt = self._get_rgba_face(alt=True)
            edgecolor = self.get_markeredgecolor()
            if is_string_like(edgecolor) and edgecolor.lower() == 'none':
                gc.set_linewidth(0)
                gc.set_foreground(rgbaFace, isRGBA=True)
            else:
                gc.set_foreground(edgecolor)
                gc.set_linewidth(self._markeredgewidth)

            marker = self._marker
            tpath, affine = transf_path.get_transformed_points_and_affine()
            if len(tpath.vertices):
                # subsample the markers if markevery is not None
                markevery = self.get_markevery()
                if markevery is not None:
                    subsampled = _mark_every_path(markevery, tpath, affine,
                                                  self.axes.transAxes)
                else:
                    subsampled = tpath

                snap = marker.get_snap_threshold()
                if type(snap) == float:
                    snap = renderer.points_to_pixels(self._markersize) >= snap
                gc.set_snap(snap)
                gc.set_joinstyle(marker.get_joinstyle())
                gc.set_capstyle(marker.get_capstyle())
                marker_path = marker.get_path()
                marker_trans = marker.get_transform()
                w = renderer.points_to_pixels(self._markersize)
                if marker.get_marker() != ',':
                    # Don't scale for pixels, and don't stroke them
                    marker_trans = marker_trans.scale(w)
                else:
                    gc.set_linewidth(0)
                if rgbaFace is not None:
                    gc.set_alpha(rgbaFace[3])

                renderer.draw_markers(gc, marker_path, marker_trans,
                                      subsampled, affine.frozen(), rgbaFace)

                alt_marker_path = marker.get_alt_path()
                if alt_marker_path:
                    if rgbaFaceAlt is not None:
                        gc.set_alpha(rgbaFaceAlt[3])
                    alt_marker_trans = marker.get_alt_transform()
                    alt_marker_trans = alt_marker_trans.scale(w)

                    renderer.draw_markers(gc, alt_marker_path,
                                          alt_marker_trans, subsampled,
                                          affine.frozen(), rgbaFaceAlt)

            gc.restore()

        gc.restore()
        renderer.close_group('line2d')

    def get_antialiased(self):
        return self._antialiased

    def get_color(self):
        return self._color

    def get_drawstyle(self):
        return self._drawstyle

    def get_linestyle(self):
        return self._linestyle

    def get_linewidth(self):
        return self._linewidth

    def get_marker(self):
        return self._marker.get_marker()

    def get_markeredgecolor(self):
        mec = self._markeredgecolor
        if (is_string_like(mec) and mec == 'auto'):
            if self._marker.get_marker() in ('.', ','):
                return self._color
            if self._marker.is_filled() and self.get_fillstyle() != 'none':
                return 'k'  # Bad hard-wired default...
            else:
                return self._color
        else:
            return mec

    def get_markeredgewidth(self):
        return self._markeredgewidth

    def _get_markerfacecolor(self, alt=False):
        if alt:
            fc = self._markerfacecoloralt
        else:
            fc = self._markerfacecolor

        if (is_string_like(fc) and fc.lower() == 'auto'):
            if self.get_fillstyle() == 'none':
                return 'none'
            else:
                return self._color
        else:
            return fc

    def get_markerfacecolor(self):
        return self._get_markerfacecolor(alt=False)

    def get_markerfacecoloralt(self):
        return self._get_markerfacecolor(alt=True)

    def get_markersize(self):
        return self._markersize

    def get_data(self, orig=True):
        """
        Return the xdata, ydata.

        If *orig* is *True*, return the original data.
        """
        return self.get_xdata(orig=orig), self.get_ydata(orig=orig)

    def get_xdata(self, orig=True):
        """
        Return the xdata.

        If *orig* is *True*, return the original data, else the
        processed data.
        """
        if orig:
            return self._xorig
        if self._invalidx:
            self.recache()
        return self._x

    def get_ydata(self, orig=True):
        """
        Return the ydata.

        If *orig* is *True*, return the original data, else the
        processed data.
        """
        if orig:
            return self._yorig
        if self._invalidy:
            self.recache()
        return self._y

    def get_path(self):
        """
        Return the :class:`~matplotlib.path.Path` object associated
        with this line.
        """
        if self._invalidy or self._invalidx:
            self.recache()
        return self._path

    def get_xydata(self):
        """
        Return the *xy* data as a Nx2 numpy array.
        """
        if self._invalidy or self._invalidx:
            self.recache()
        return self._xy

    def set_antialiased(self, b):
        """
        True if line should be drawin with antialiased rendering

        ACCEPTS: [True | False]
        """
        self._antialiased = b

    def set_color(self, color):
        """
        Set the color of the line

        ACCEPTS: any matplotlib color
        """
        self._color = color

    def set_drawstyle(self, drawstyle):
        """
        Set the drawstyle of the plot

        'default' connects the points with lines. The steps variants
        produce step-plots. 'steps' is equivalent to 'steps-pre' and
        is maintained for backward-compatibility.

        ACCEPTS: ['default' | 'steps' | 'steps-pre' | 'steps-mid' |
                  'steps-post']
        """
        self._drawstyle = drawstyle

    def set_linewidth(self, w):
        """
        Set the line width in points

        ACCEPTS: float value in points
        """
        self._linewidth = float(w)

    def set_linestyle(self, linestyle):
        """
        Set the linestyle of the line (also accepts drawstyles)


        ================    =================
        linestyle           description
        ================    =================
        ``'-'``             solid
        ``'--'``            dashed
        ``'-.'``            dash_dot
        ``':'``             dotted
        ``'None'``          draw nothing
        ``' '``             draw nothing
        ``''``              draw nothing
        ================    =================

        'steps' is equivalent to 'steps-pre' and is maintained for
        backward-compatibility.

        .. seealso::

            :meth:`set_drawstyle`
               To set the drawing style (stepping) of the plot.

        ACCEPTS: [``'-'`` | ``'--'`` | ``'-.'`` | ``':'`` | ``'None'`` |
                  ``' '`` | ``''``]

        and any drawstyle in combination with a linestyle, e.g., ``'steps--'``.
        """

        for ds in self.drawStyleKeys:  # long names are first in the list
            if linestyle.startswith(ds):
                self.set_drawstyle(ds)
                if len(linestyle) > len(ds):
                    linestyle = linestyle[len(ds):]
                else:
                    linestyle = '-'
                break

        if linestyle not in self._lineStyles:
            if linestyle in ls_mapper:
                linestyle = ls_mapper[linestyle]
            else:
                verbose.report('Unrecognized line style %s, %s' %
                               (linestyle, type(linestyle)))
        if linestyle in [' ', '']:
            linestyle = 'None'
        self._linestyle = linestyle

    @docstring.dedent_interpd
    def set_marker(self, marker):
        """
        Set the line marker

        ACCEPTS: :mod:`A valid marker style <matplotlib.markers>`

        Parameters
        -----------

        marker: marker style
            See `~matplotlib.markers` for full description of possible
            argument

        """
        self._marker.set_marker(marker)

    def set_markeredgecolor(self, ec):
        """
        Set the marker edge color

        ACCEPTS: any matplotlib color
        """
        if ec is None:
            ec = 'auto'
        self._markeredgecolor = ec

    def set_markeredgewidth(self, ew):
        """
        Set the marker edge width in points

        ACCEPTS: float value in points
        """
        if ew is None:
            ew = rcParams['lines.markeredgewidth']
        self._markeredgewidth = ew

    def set_markerfacecolor(self, fc):
        """
        Set the marker face color.

        ACCEPTS: any matplotlib color
        """
        if fc is None:
            fc = 'auto'

        self._markerfacecolor = fc

    def set_markerfacecoloralt(self, fc):
        """
        Set the alternate marker face color.

        ACCEPTS: any matplotlib color
        """
        if fc is None:
            fc = 'auto'

        self._markerfacecoloralt = fc

    def set_markersize(self, sz):
        """
        Set the marker size in points

        ACCEPTS: float
        """
        self._markersize = sz

    def set_xdata(self, x):
        """
        Set the data np.array for x

        ACCEPTS: 1D array
        """
        self._xorig = x
        self._invalidx = True

    def set_ydata(self, y):
        """
        Set the data np.array for y

        ACCEPTS: 1D array
        """
        self._yorig = y
        self._invalidy = True

    def set_dashes(self, seq):
        """
        Set the dash sequence, sequence of dashes with on off ink in
        points.  If seq is empty or if seq = (None, None), the
        linestyle will be set to solid.

        ACCEPTS: sequence of on/off ink in points
        """
        if seq == (None, None) or len(seq) == 0:
            self.set_linestyle('-')
        else:
            self.set_linestyle('--')
        self._dashSeq = seq  # TODO: offset ignored for now

    def _draw_lines(self, renderer, gc, path, trans):
        self._lineFunc(renderer, gc, path, trans)

    def _draw_steps_pre(self, renderer, gc, path, trans):
        vertices = self._xy
        steps = ma.zeros((2 * len(vertices) - 1, 2), np.float_)

        steps[0::2, 0], steps[1::2, 0] = vertices[:, 0], vertices[:-1, 0]
        steps[0::2, 1], steps[1:-1:2, 1] = vertices[:, 1], vertices[1:, 1]

        path = Path(steps)
        path = path.transformed(self.get_transform())
        self._lineFunc(renderer, gc, path, IdentityTransform())

    def _draw_steps_post(self, renderer, gc, path, trans):
        vertices = self._xy
        steps = ma.zeros((2 * len(vertices) - 1, 2), np.float_)

        steps[::2, 0], steps[1:-1:2, 0] = vertices[:, 0], vertices[1:, 0]
        steps[0::2, 1], steps[1::2, 1] = vertices[:, 1], vertices[:-1, 1]

        path = Path(steps)
        path = path.transformed(self.get_transform())
        self._lineFunc(renderer, gc, path, IdentityTransform())

    def _draw_steps_mid(self, renderer, gc, path, trans):
        vertices = self._xy
        steps = ma.zeros((2 * len(vertices), 2), np.float_)

        steps[1:-1:2, 0] = 0.5 * (vertices[:-1, 0] + vertices[1:, 0])
        steps[2::2, 0] = 0.5 * (vertices[:-1, 0] + vertices[1:, 0])
        steps[0, 0] = vertices[0, 0]
        steps[-1, 0] = vertices[-1, 0]
        steps[0::2, 1], steps[1::2, 1] = vertices[:, 1], vertices[:, 1]

        path = Path(steps)
        path = path.transformed(self.get_transform())
        self._lineFunc(renderer, gc, path, IdentityTransform())

    def _draw_solid(self, renderer, gc, path, trans):
        gc.set_linestyle('solid')
        renderer.draw_path(gc, path, trans)

    def _draw_dashed(self, renderer, gc, path, trans):
        gc.set_linestyle('dashed')
        if self._dashSeq is not None:
            gc.set_dashes(0, self._dashSeq)

        renderer.draw_path(gc, path, trans)

    def _draw_dash_dot(self, renderer, gc, path, trans):
        gc.set_linestyle('dashdot')
        renderer.draw_path(gc, path, trans)

    def _draw_dotted(self, renderer, gc, path, trans):
        gc.set_linestyle('dotted')
        renderer.draw_path(gc, path, trans)

    def update_from(self, other):
        """copy properties from other to self"""
        Artist.update_from(self, other)
        self._linestyle = other._linestyle
        self._linewidth = other._linewidth
        self._color = other._color
        self._markersize = other._markersize
        self._markerfacecolor = other._markerfacecolor
        self._markerfacecoloralt = other._markerfacecoloralt
        self._markeredgecolor = other._markeredgecolor
        self._markeredgewidth = other._markeredgewidth
        self._dashSeq = other._dashSeq
        self._dashcapstyle = other._dashcapstyle
        self._dashjoinstyle = other._dashjoinstyle
        self._solidcapstyle = other._solidcapstyle
        self._solidjoinstyle = other._solidjoinstyle

        self._linestyle = other._linestyle
        self._marker = MarkerStyle(other._marker.get_marker(),
                                   other._marker.get_fillstyle())
        self._drawstyle = other._drawstyle

    def _get_rgb_face(self, alt=False):
        facecolor = self._get_markerfacecolor(alt=alt)
        if is_string_like(facecolor) and facecolor.lower() == 'none':
            rgbFace = None
        else:
            rgbFace = colorConverter.to_rgb(facecolor)
        return rgbFace

    def _get_rgba_face(self, alt=False):
        facecolor = self._get_markerfacecolor(alt=alt)
        if is_string_like(facecolor) and facecolor.lower() == 'none':
            rgbaFace = None
        else:
            rgbaFace = colorConverter.to_rgba(facecolor, self._alpha)
        return rgbaFace

    def _get_rgba_ln_color(self, alt=False):
        return colorConverter.to_rgba(self._color, self._alpha)

    # some aliases....
    def set_aa(self, val):
        'alias for set_antialiased'
        self.set_antialiased(val)

    def set_c(self, val):
        'alias for set_color'
        self.set_color(val)

    def set_ls(self, val):
        """alias for set_linestyle"""
        self.set_linestyle(val)

    def set_lw(self, val):
        """alias for set_linewidth"""
        self.set_linewidth(val)

    def set_mec(self, val):
        """alias for set_markeredgecolor"""
        self.set_markeredgecolor(val)

    def set_mew(self, val):
        """alias for set_markeredgewidth"""
        self.set_markeredgewidth(val)

    def set_mfc(self, val):
        """alias for set_markerfacecolor"""
        self.set_markerfacecolor(val)

    def set_mfcalt(self, val):
        """alias for set_markerfacecoloralt"""
        self.set_markerfacecoloralt(val)

    def set_ms(self, val):
        """alias for set_markersize"""
        self.set_markersize(val)

    def get_aa(self):
        """alias for get_antialiased"""
        return self.get_antialiased()

    def get_c(self):
        """alias for get_color"""
        return self.get_color()

    def get_ls(self):
        """alias for get_linestyle"""
        return self.get_linestyle()

    def get_lw(self):
        """alias for get_linewidth"""
        return self.get_linewidth()

    def get_mec(self):
        """alias for get_markeredgecolor"""
        return self.get_markeredgecolor()

    def get_mew(self):
        """alias for get_markeredgewidth"""
        return self.get_markeredgewidth()

    def get_mfc(self):
        """alias for get_markerfacecolor"""
        return self.get_markerfacecolor()

    def get_mfcalt(self, alt=False):
        """alias for get_markerfacecoloralt"""
        return self.get_markerfacecoloralt()

    def get_ms(self):
        """alias for get_markersize"""
        return self.get_markersize()

    def set_dash_joinstyle(self, s):
        """
        Set the join style for dashed linestyles
        ACCEPTS: ['miter' | 'round' | 'bevel']
        """
        s = s.lower()
        if s not in self.validJoin:
            raise ValueError('set_dash_joinstyle passed "%s";\n' % (s, ) +
                             'valid joinstyles are %s' % (self.validJoin, ))
        self._dashjoinstyle = s

    def set_solid_joinstyle(self, s):
        """
        Set the join style for solid linestyles
        ACCEPTS: ['miter' | 'round' | 'bevel']
        """
        s = s.lower()
        if s not in self.validJoin:
            raise ValueError('set_solid_joinstyle passed "%s";\n' % (s, ) +
                             'valid joinstyles are %s' % (self.validJoin, ))
        self._solidjoinstyle = s

    def get_dash_joinstyle(self):
        """
        Get the join style for dashed linestyles
        """
        return self._dashjoinstyle

    def get_solid_joinstyle(self):
        """
        Get the join style for solid linestyles
        """
        return self._solidjoinstyle

    def set_dash_capstyle(self, s):
        """
        Set the cap style for dashed linestyles

        ACCEPTS: ['butt' | 'round' | 'projecting']
        """
        s = s.lower()
        if s not in self.validCap:
            raise ValueError('set_dash_capstyle passed "%s";\n' % (s, ) +
                             'valid capstyles are %s' % (self.validCap, ))

        self._dashcapstyle = s

    def set_solid_capstyle(self, s):
        """
        Set the cap style for solid linestyles

        ACCEPTS: ['butt' | 'round' |  'projecting']
        """
        s = s.lower()
        if s not in self.validCap:
            raise ValueError('set_solid_capstyle passed "%s";\n' % (s, ) +
                             'valid capstyles are %s' % (self.validCap, ))

        self._solidcapstyle = s

    def get_dash_capstyle(self):
        """
        Get the cap style for dashed linestyles
        """
        return self._dashcapstyle

    def get_solid_capstyle(self):
        """
        Get the cap style for solid linestyles
        """
        return self._solidcapstyle

    def is_dashed(self):
        'return True if line is dashstyle'
        return self._linestyle in ('--', '-.', ':')
Exemplo n.º 16
0
class Line2D(Artist):
    """
    A line - the line can have both a solid linestyle connecting all
    the vertices, and a marker at each vertex.  Additionally, the
    drawing of the solid line is influenced by the drawstyle, eg one
    can create "stepped" lines in various styles.


    """
    lineStyles = _lineStyles =  { # hidden names deprecated
        '-'          : '_draw_solid',
        '--'         : '_draw_dashed',
        '-.'         : '_draw_dash_dot',
        ':'          : '_draw_dotted',
        'None'       : '_draw_nothing',
        ' '          : '_draw_nothing',
        ''           : '_draw_nothing',
    }

    _drawStyles_l = {
        'default'    : '_draw_lines',
        'steps-mid'  : '_draw_steps_mid',
        'steps-pre'  : '_draw_steps_pre',
        'steps-post' : '_draw_steps_post',
    }

    _drawStyles_s = {
        'steps'      : '_draw_steps_pre',
    }
    drawStyles = {}
    drawStyles.update(_drawStyles_l)
    drawStyles.update(_drawStyles_s)
    # Need a list ordered with long names first:
    drawStyleKeys = _drawStyles_l.keys() + _drawStyles_s.keys()

    # Referenced here to maintain API.  These are defined in
    # MarkerStyle
    markers = MarkerStyle.markers
    filled_markers = MarkerStyle.filled_markers
    fillStyles = MarkerStyle.fillstyles

    zorder = 2
    validCap = ('butt', 'round', 'projecting')
    validJoin =   ('miter', 'round', 'bevel')

    def __str__(self):
        if self._label != "":
            return "Line2D(%s)"%(self._label)
        elif hasattr(self, '_x') and len(self._x) > 3:
            return "Line2D((%g,%g),(%g,%g),...,(%g,%g))"\
                %(self._x[0],self._y[0],self._x[0],self._y[0],self._x[-1],self._y[-1])
        elif hasattr(self, '_x'):
            return "Line2D(%s)"\
                %(",".join(["(%g,%g)"%(x,y) for x,y in zip(self._x,self._y)]))
        else:
            return "Line2D()"

    def __init__(self, xdata, ydata,
                 linewidth       = None, # all Nones default to rc
                 linestyle       = None,
                 color           = None,
                 marker          = None,
                 markersize      = None,
                 markeredgewidth = None,
                 markeredgecolor = None,
                 markerfacecolor = None,
                 markerfacecoloralt = 'none',
                 fillstyle       = 'full',
                 antialiased     = None,
                 dash_capstyle   = None,
                 solid_capstyle  = None,
                 dash_joinstyle  = None,
                 solid_joinstyle = None,
                 pickradius      = 5,
                 drawstyle       = None,
                 markevery       = None,
                 **kwargs
                 ):
        """
        Create a :class:`~matplotlib.lines.Line2D` instance with *x*
        and *y* data in sequences *xdata*, *ydata*.

        The kwargs are :class:`~matplotlib.lines.Line2D` properties:

        %(Line2D)s

        See :meth:`set_linestyle` for a decription of the line styles,
        :meth:`set_marker` for a description of the markers, and
        :meth:`set_drawstyle` for a description of the draw styles.

        """
        Artist.__init__(self)

        #convert sequences to numpy arrays
        if not iterable(xdata):
            raise RuntimeError('xdata must be a sequence')
        if not iterable(ydata):
            raise RuntimeError('ydata must be a sequence')

        if linewidth is None   : linewidth=rcParams['lines.linewidth']

        if linestyle is None   : linestyle=rcParams['lines.linestyle']
        if marker is None      : marker=rcParams['lines.marker']
        if color is None       : color=rcParams['lines.color']

        if markersize is None  : markersize=rcParams['lines.markersize']
        if antialiased is None : antialiased=rcParams['lines.antialiased']
        if dash_capstyle is None : dash_capstyle=rcParams['lines.dash_capstyle']
        if dash_joinstyle is None : dash_joinstyle=rcParams['lines.dash_joinstyle']
        if solid_capstyle is None : solid_capstyle=rcParams['lines.solid_capstyle']
        if solid_joinstyle is None : solid_joinstyle=rcParams['lines.solid_joinstyle']

        if drawstyle is None : drawstyle='default'

        self.set_dash_capstyle(dash_capstyle)
        self.set_dash_joinstyle(dash_joinstyle)
        self.set_solid_capstyle(solid_capstyle)
        self.set_solid_joinstyle(solid_joinstyle)


        self.set_linestyle(linestyle)
        self.set_drawstyle(drawstyle)
        self.set_linewidth(linewidth)
        self.set_color(color)
        self._marker = MarkerStyle()
        self.set_marker(marker)
        self.set_markevery(markevery)
        self.set_antialiased(antialiased)
        self.set_markersize(markersize)
        self._dashSeq = None


        self.set_markerfacecolor(markerfacecolor)
        self.set_markerfacecoloralt(markerfacecoloralt)
        self.set_markeredgecolor(markeredgecolor)
        self.set_markeredgewidth(markeredgewidth)
        self.set_fillstyle(fillstyle)

        self.verticalOffset = None

        # update kwargs before updating data to give the caller a
        # chance to init axes (and hence unit support)
        self.update(kwargs)
        self.pickradius = pickradius
        self.ind_offset = 0
        if is_numlike(self._picker):
            self.pickradius = self._picker

        self._xorig = np.asarray([])
        self._yorig = np.asarray([])
        self._invalidx = True
        self._invalidy = True
        self.set_data(xdata, ydata)

    def contains(self, mouseevent):
        """
        Test whether the mouse event occurred on the line.  The pick
        radius determines the precision of the location test (usually
        within five points of the value).  Use
        :meth:`~matplotlib.lines.Line2D.get_pickradius` or
        :meth:`~matplotlib.lines.Line2D.set_pickradius` to view or
        modify it.

        Returns *True* if any values are within the radius along with
        ``{'ind': pointlist}``, where *pointlist* is the set of points
        within the radius.

        TODO: sort returned indices by distance
        """
        if callable(self._contains):
            return self._contains(self,mouseevent)

        if not is_numlike(self.pickradius):
            raise ValueError("pick radius should be a distance")

        # Make sure we have data to plot
        if self._invalidy or self._invalidx:
            self.recache()
        if len(self._xy)==0: return False,{}

        # Convert points to pixels
        if self._transformed_path is None:
            self._transform_path()
        path, affine = self._transformed_path.get_transformed_path_and_affine()
        path = affine.transform_path(path)
        xy = path.vertices
        xt = xy[:, 0]
        yt = xy[:, 1]

        # Convert pick radius from points to pixels
        if self.figure == None:
            warning.warn('no figure set when check if mouse is on line')
            pixels = self.pickradius
        else:
            pixels = self.figure.dpi/72. * self.pickradius

        # the math involved in checking for containment (here and inside of segment_hits) assumes
        # that it is OK to overflow.  In case the application has set the error flags such that
        # an exception is raised on overflow, we temporarily set the appropriate error flags here
        # and set them back when we are finished. 
        olderrflags = np.seterr(all='ignore')
        try:
            # Check for collision
            if self._linestyle in ['None',None]:
                # If no line, return the nearby point(s)
                d = (xt-mouseevent.x)**2 + (yt-mouseevent.y)**2
                ind, = np.nonzero(np.less_equal(d, pixels**2))
            else:
                # If line, return the nearby segment(s)
                ind = segment_hits(mouseevent.x,mouseevent.y,xt,yt,pixels)
        finally:
            np.seterr(**olderrflags)

        ind += self.ind_offset

        # Debugging message
        if False and self._label != '':
            print("Checking line",self._label,"at",mouseevent.x,mouseevent.y)
            print('xt', xt)
            print('yt', yt)
            #print 'dx,dy', (xt-mouseevent.x)**2., (yt-mouseevent.y)**2.
            print('ind',ind)

        # Return the point(s) within radius
        return len(ind)>0,dict(ind=ind)

    def get_pickradius(self):
        'return the pick radius used for containment tests'
        return self.pickradius

    def set_pickradius(self,d):
        """Sets the pick radius used for containment tests

        ACCEPTS: float distance in points
        """
        self.pickradius = d

    def get_fillstyle(self):
        """
        return the marker fillstyle
        """
        return self._marker.get_fillstyle()

    def set_fillstyle(self, fs):
        """
        Set the marker fill style; 'full' means fill the whole marker.
        'none' means no filling; other options are for half-filled markers.

        ACCEPTS: ['full' | 'left' | 'right' | 'bottom' | 'top' | 'none']
        """
        self._marker.set_fillstyle(fs)

    def set_markevery(self, every):
        """
        Set the markevery property to subsample the plot when using
        markers.  Eg if ``markevery=5``, every 5-th marker will be
        plotted.  *every* can be

        None
            Every point will be plotted

        an integer N
            Every N-th marker will be plotted starting with marker 0

        A length-2 tuple of integers
            every=(start, N) will start at point start and plot every N-th marker


        ACCEPTS: None | integer | (startind, stride)

        """
        self._markevery = every

    def get_markevery(self):
        'return the markevery setting'
        return self._markevery

    def set_picker(self,p):
        """Sets the event picker details for the line.

        ACCEPTS: float distance in points or callable pick function
        ``fn(artist, event)``
        """
        if callable(p):
            self._contains = p
        else:
            self.pickradius = p
        self._picker = p

    def get_window_extent(self, renderer):
        bbox = Bbox.unit()
        bbox.update_from_data_xy(self.get_transform().transform(self.get_xydata()),
                                 ignore=True)
        # correct for marker size, if any
        if self._marker:
            ms = (self._markersize / 72.0 * self.figure.dpi) * 0.5
            bbox = bbox.padded(ms)
        return bbox

    def set_axes(self, ax):
        Artist.set_axes(self, ax)
        if ax.xaxis is not None:
            self._xcid = ax.xaxis.callbacks.connect('units', self.recache_always)
        if ax.yaxis is not None:
            self._ycid = ax.yaxis.callbacks.connect('units', self.recache_always)
    set_axes.__doc__ = Artist.set_axes.__doc__

    def set_data(self, *args):
        """
        Set the x and y data

        ACCEPTS: 2D array (rows are x, y) or two 1D arrays
        """
        if len(args)==1:
            x, y = args[0]
        else:
            x, y = args

        self.set_xdata(x)
        self.set_ydata(y)

    def recache_always(self):
        self.recache(always=True)

    def recache(self, always=False):
        if always or self._invalidx:
            xconv = self.convert_xunits(self._xorig)
            if ma.isMaskedArray(self._xorig):
                x = ma.asarray(xconv, np.float_)
            else:
                x = np.asarray(xconv, np.float_)
            x = x.ravel()
        else:
            x = self._x
        if always or self._invalidy:
            yconv = self.convert_yunits(self._yorig)
            if ma.isMaskedArray(self._yorig):
                y = ma.asarray(yconv, np.float_)
            else:
                y = np.asarray(yconv, np.float_)
            y = y.ravel()
        else:
            y = self._y

        if len(x)==1 and len(y)>1:
            x = x * np.ones(y.shape, np.float_)
        if len(y)==1 and len(x)>1:
            y = y * np.ones(x.shape, np.float_)

        if len(x) != len(y):
            raise RuntimeError('xdata and ydata must be the same length')

        x = x.reshape((len(x), 1))
        y = y.reshape((len(y), 1))

        if ma.isMaskedArray(x) or ma.isMaskedArray(y):
            self._xy = ma.concatenate((x, y), 1)
        else:
            self._xy = np.concatenate((x, y), 1)
        self._x = self._xy[:, 0] # just a view
        self._y = self._xy[:, 1] # just a view

        self._subslice = False
        if (self.axes and len(x) > 100 and self._is_sorted(x) and
            self.axes.name == 'rectilinear' and
            self.axes.get_xscale() == 'linear' and
            self._markevery is None):
            self._subslice = True
        if hasattr(self, '_path'):
            interpolation_steps = self._path._interpolation_steps
        else:
            interpolation_steps = 1
        self._path = Path(self._xy, None, interpolation_steps)
        self._transformed_path = None
        self._invalidx = False
        self._invalidy = False

    def _transform_path(self, subslice=None):
        # Masked arrays are now handled by the Path class itself
        if subslice is not None:
            _path = Path(self._xy[subslice,:])
        else:
            _path = self._path
        self._transformed_path = TransformedPath(_path, self.get_transform())


    def set_transform(self, t):
        """
        set the Transformation instance used by this artist

        ACCEPTS: a :class:`matplotlib.transforms.Transform` instance
        """
        Artist.set_transform(self, t)
        self._invalidx = True
        self._invalidy = True

    def _is_sorted(self, x):
        "return true if x is sorted"
        if len(x)<2: return 1
        return np.alltrue(x[1:]-x[0:-1]>=0)

    @allow_rasterization
    def draw(self, renderer):
        if self._invalidy or self._invalidx:
            self.recache()
        self.ind_offset = 0  # Needed for contains() method.
        if self._subslice and self.axes:
            # Need to handle monotonically decreasing case also...
            x0, x1 = self.axes.get_xbound()
            i0, = self._x.searchsorted([x0], 'left')
            i1, = self._x.searchsorted([x1], 'right')
            subslice = slice(max(i0-1, 0), i1+1)
            self.ind_offset = subslice.start
            self._transform_path(subslice)
        if self._transformed_path is None:
            self._transform_path()

        if not self.get_visible(): return

        renderer.open_group('line2d', self.get_gid())
        gc = renderer.new_gc()
        self._set_gc_clip(gc)

        gc.set_foreground(self._color)
        gc.set_antialiased(self._antialiased)
        gc.set_linewidth(self._linewidth)
        gc.set_alpha(self._alpha)
        if self.is_dashed():
            cap = self._dashcapstyle
            join = self._dashjoinstyle
        else:
            cap = self._solidcapstyle
            join = self._solidjoinstyle
        gc.set_joinstyle(join)
        gc.set_capstyle(cap)
        gc.set_snap(self.get_snap())

        funcname = self._lineStyles.get(self._linestyle, '_draw_nothing')
        if funcname != '_draw_nothing':
            tpath, affine = self._transformed_path.get_transformed_path_and_affine()
            if len(tpath.vertices):
                self._lineFunc = getattr(self, funcname)
                funcname = self.drawStyles.get(self._drawstyle, '_draw_lines')
                drawFunc = getattr(self, funcname)
                drawFunc(renderer, gc, tpath, affine.frozen())

        if self._marker:
            gc = renderer.new_gc()
            self._set_gc_clip(gc)
            rgbFace = self._get_rgb_face()
            rgbFaceAlt = self._get_rgb_face(alt=True)
            edgecolor = self.get_markeredgecolor()
            if is_string_like(edgecolor) and edgecolor.lower() == 'none':
                gc.set_linewidth(0)
                gc.set_foreground(rgbFace)
            else:
                gc.set_foreground(edgecolor)
                gc.set_linewidth(self._markeredgewidth)
            gc.set_alpha(self._alpha)
            marker = self._marker
            tpath, affine = self._transformed_path.get_transformed_points_and_affine()
            if len(tpath.vertices):
                # subsample the markers if markevery is not None
                markevery = self.get_markevery()
                if markevery is not None:
                    if iterable(markevery):
                        startind, stride = markevery
                    else:
                        startind, stride = 0, markevery
                    if tpath.codes is not None:
                        codes = tpath.codes[startind::stride]
                    else:
                        codes = None
                    vertices = tpath.vertices[startind::stride]
                    subsampled = Path(vertices, codes)
                else:
                    subsampled = tpath

                snap = marker.get_snap_threshold()
                if type(snap) == float:
                    snap = renderer.points_to_pixels(self._markersize) >= snap
                gc.set_snap(snap)
                gc.set_joinstyle(marker.get_joinstyle())
                gc.set_capstyle(marker.get_capstyle())
                marker_path = marker.get_path()
                marker_trans = marker.get_transform()
                w = renderer.points_to_pixels(self._markersize)
                if marker.get_marker() != ',':
                    # Don't scale for pixels, and don't stroke them
                    marker_trans = marker_trans.scale(w)
                else:
                    gc.set_linewidth(0)
                renderer.draw_markers(
                    gc, marker_path, marker_trans, subsampled, affine.frozen(),
                    rgbFace)
                alt_marker_path = marker.get_alt_path()
                if alt_marker_path:
                    alt_marker_trans = marker.get_alt_transform()
                    alt_marker_trans = alt_marker_trans.scale(w)
                    renderer.draw_markers(
                        gc, alt_marker_path, alt_marker_trans, subsampled,
                        affine.frozen(), rgbFaceAlt)

            gc.restore()

        gc.restore()
        renderer.close_group('line2d')

    def get_antialiased(self): return self._antialiased
    def get_color(self): return self._color
    def get_drawstyle(self): return self._drawstyle
    def get_linestyle(self): return self._linestyle

    def get_linewidth(self): return self._linewidth
    def get_marker(self): return self._marker.get_marker()

    def get_markeredgecolor(self):
        mec = self._markeredgecolor
        if (is_string_like(mec) and mec == 'auto'):
            if self._marker.get_marker() in ('.', ','):
                return self._color
            if self._marker.is_filled() and self.get_fillstyle() != 'none':
                return 'k'  # Bad hard-wired default...
            else:
                return self._color
        else:
            return mec

    def get_markeredgewidth(self): return self._markeredgewidth

    def _get_markerfacecolor(self, alt=False):
        if alt:
            fc = self._markerfacecoloralt
        else:
            fc = self._markerfacecolor

        if (is_string_like(fc) and fc.lower() == 'auto'):
            if self.get_fillstyle() == 'none':
                return 'none'
            else:
                return self._color
        else:
            return fc

    def get_markerfacecolor(self):
        return self._get_markerfacecolor(alt=False)

    def get_markerfacecoloralt(self):
        return self._get_markerfacecolor(alt=True)

    def get_markersize(self): return self._markersize

    def get_data(self, orig=True):
        """
        Return the xdata, ydata.

        If *orig* is *True*, return the original data
        """
        return self.get_xdata(orig=orig), self.get_ydata(orig=orig)


    def get_xdata(self, orig=True):
        """
        Return the xdata.

        If *orig* is *True*, return the original data, else the
        processed data.
        """
        if orig:
            return self._xorig
        if self._invalidx:
            self.recache()
        return self._x

    def get_ydata(self, orig=True):
        """
        Return the ydata.

        If *orig* is *True*, return the original data, else the
        processed data.
        """
        if orig:
            return self._yorig
        if self._invalidy:
            self.recache()
        return self._y

    def get_path(self):
        """
        Return the :class:`~matplotlib.path.Path` object associated
        with this line.
        """
        if self._invalidy or self._invalidx:
            self.recache()
        return self._path

    def get_xydata(self):
        """
        Return the *xy* data as a Nx2 numpy array.
        """
        if self._invalidy or self._invalidx:
            self.recache()
        return self._xy

    def set_antialiased(self, b):
        """
        True if line should be drawin with antialiased rendering

        ACCEPTS: [True | False]
        """
        self._antialiased = b

    def set_color(self, color):
        """
        Set the color of the line

        ACCEPTS: any matplotlib color
        """
        self._color = color

    def set_drawstyle(self, drawstyle):
        """
        Set the drawstyle of the plot

        'default' connects the points with lines. The steps variants
        produce step-plots. 'steps' is equivalent to 'steps-pre' and
        is maintained for backward-compatibility.

        ACCEPTS: [ 'default' | 'steps' | 'steps-pre' | 'steps-mid' | 'steps-post' ]
        """
        self._drawstyle = drawstyle

    def set_linewidth(self, w):
        """
        Set the line width in points

        ACCEPTS: float value in points
        """
        self._linewidth = w

    def set_linestyle(self, linestyle):
        """
        Set the linestyle of the line (also accepts drawstyles)


        ================    =================
        linestyle           description
        ================    =================
        ``'-'``             solid
        ``'--'``            dashed
        ``'-.'``            dash_dot
        ``':'``             dotted
        ``'None'``          draw nothing
        ``' '``             draw nothing
        ``''``              draw nothing
        ================    =================

        'steps' is equivalent to 'steps-pre' and is maintained for
        backward-compatibility.

        .. seealso::

            :meth:`set_drawstyle`
               To set the drawing style (stepping) of the plot.

        ACCEPTS: [ ``'-'`` | ``'--'`` | ``'-.'`` | ``':'`` | ``'None'`` | ``' '`` | ``''`` ]
        and any drawstyle in combination with a linestyle, e.g. ``'steps--'``.
        """

        for ds in self.drawStyleKeys:  # long names are first in the list
            if linestyle.startswith(ds):
                self.set_drawstyle(ds)
                if len(linestyle) > len(ds):
                    linestyle = linestyle[len(ds):]
                else:
                    linestyle = '-'
                break

        if linestyle not in self._lineStyles:
            if linestyle in ls_mapper:
                linestyle = ls_mapper[linestyle]
            else:
                verbose.report('Unrecognized line style %s, %s' %
                                            (linestyle, type(linestyle)))
        if linestyle in [' ','']:
            linestyle = 'None'
        self._linestyle = linestyle

    @docstring.dedent_interpd
    def set_marker(self, marker):
        """
        Set the line marker

        %(MarkerTable)s

        %(MarkerAccepts)s
        """
        self._marker.set_marker(marker)

    def set_markeredgecolor(self, ec):
        """
        Set the marker edge color

        ACCEPTS: any matplotlib color
        """
        if ec is None :
            ec = 'auto'
        self._markeredgecolor = ec

    def set_markeredgewidth(self, ew):
        """
        Set the marker edge width in points

        ACCEPTS: float value in points
        """
        if ew is None :
            ew = rcParams['lines.markeredgewidth']
        self._markeredgewidth = ew

    def set_markerfacecolor(self, fc):
        """
        Set the marker face color.

        ACCEPTS: any matplotlib color
        """
        if fc is None:
            fc = 'auto'

        self._markerfacecolor = fc

    def set_markerfacecoloralt(self, fc):
        """
        Set the alternate marker face color.

        ACCEPTS: any matplotlib color
        """
        if fc is None:
            fc = 'auto'

        self._markerfacecoloralt = fc

    def set_markersize(self, sz):
        """
        Set the marker size in points

        ACCEPTS: float
        """
        self._markersize = sz

    def set_xdata(self, x):
        """
        Set the data np.array for x

        ACCEPTS: 1D array
        """
        self._xorig = x
        self._invalidx = True

    def set_ydata(self, y):
        """
        Set the data np.array for y

        ACCEPTS: 1D array
        """
        self._yorig = y
        self._invalidy = True

    def set_dashes(self, seq):
        """
        Set the dash sequence, sequence of dashes with on off ink in
        points.  If seq is empty or if seq = (None, None), the
        linestyle will be set to solid.

        ACCEPTS: sequence of on/off ink in points
        """
        if seq == (None, None) or len(seq)==0:
            self.set_linestyle('-')
        else:
            self.set_linestyle('--')
        self._dashSeq = seq  # TODO: offset ignored for now


    def _draw_lines(self, renderer, gc, path, trans):
        self._lineFunc(renderer, gc, path, trans)


    def _draw_steps_pre(self, renderer, gc, path, trans):
        vertices = self._xy
        steps = ma.zeros((2*len(vertices)-1, 2), np.float_)

        steps[0::2, 0], steps[1::2, 0] = vertices[:, 0], vertices[:-1, 0]
        steps[0::2, 1], steps[1:-1:2, 1] = vertices[:, 1], vertices[1:, 1]

        path = Path(steps)
        path = path.transformed(self.get_transform())
        self._lineFunc(renderer, gc, path, IdentityTransform())


    def _draw_steps_post(self, renderer, gc, path, trans):
        vertices = self._xy
        steps = ma.zeros((2*len(vertices)-1, 2), np.float_)

        steps[::2, 0], steps[1:-1:2, 0] = vertices[:, 0], vertices[1:, 0]
        steps[0::2, 1], steps[1::2, 1] = vertices[:, 1], vertices[:-1, 1]

        path = Path(steps)
        path = path.transformed(self.get_transform())
        self._lineFunc(renderer, gc, path, IdentityTransform())


    def _draw_steps_mid(self, renderer, gc, path, trans):
        vertices = self._xy
        steps = ma.zeros((2*len(vertices), 2), np.float_)

        steps[1:-1:2, 0] = 0.5 * (vertices[:-1, 0] + vertices[1:, 0])
        steps[2::2, 0] = 0.5 * (vertices[:-1, 0] + vertices[1:, 0])
        steps[0, 0] = vertices[0, 0]
        steps[-1, 0] = vertices[-1, 0]
        steps[0::2, 1], steps[1::2, 1] = vertices[:, 1], vertices[:, 1]

        path = Path(steps)
        path = path.transformed(self.get_transform())
        self._lineFunc(renderer, gc, path, IdentityTransform())


    def _draw_solid(self, renderer, gc, path, trans):
        gc.set_linestyle('solid')
        renderer.draw_path(gc, path, trans)


    def _draw_dashed(self, renderer, gc, path, trans):
        gc.set_linestyle('dashed')
        if self._dashSeq is not None:
            gc.set_dashes(0, self._dashSeq)

        renderer.draw_path(gc, path, trans)


    def _draw_dash_dot(self, renderer, gc, path, trans):
        gc.set_linestyle('dashdot')
        renderer.draw_path(gc, path, trans)


    def _draw_dotted(self, renderer, gc, path, trans):
        gc.set_linestyle('dotted')
        renderer.draw_path(gc, path, trans)


    def update_from(self, other):
        'copy properties from other to self'
        Artist.update_from(self, other)
        self._linestyle = other._linestyle
        self._linewidth = other._linewidth
        self._color = other._color
        self._markersize = other._markersize
        self._markerfacecolor = other._markerfacecolor
        self._markerfacecoloralt = other._markerfacecoloralt
        self._markeredgecolor = other._markeredgecolor
        self._markeredgewidth = other._markeredgewidth
        self._dashSeq = other._dashSeq
        self._dashcapstyle = other._dashcapstyle
        self._dashjoinstyle = other._dashjoinstyle
        self._solidcapstyle = other._solidcapstyle
        self._solidjoinstyle = other._solidjoinstyle

        self._linestyle = other._linestyle
        self._marker = MarkerStyle(other._marker.get_marker(),
                                   other._marker.get_fillstyle())
        self._drawstyle = other._drawstyle


    def _get_rgb_face(self, alt=False):
        facecolor = self._get_markerfacecolor(alt=alt)
        if is_string_like(facecolor) and facecolor.lower()=='none':
            rgbFace = None
        else:
            rgbFace = colorConverter.to_rgb(facecolor)
        return rgbFace

    # some aliases....
    def set_aa(self, val):
        'alias for set_antialiased'
        self.set_antialiased(val)

    def set_c(self, val):
        'alias for set_color'
        self.set_color(val)


    def set_ls(self, val):
        'alias for set_linestyle'
        self.set_linestyle(val)


    def set_lw(self, val):
        'alias for set_linewidth'
        self.set_linewidth(val)


    def set_mec(self, val):
        'alias for set_markeredgecolor'
        self.set_markeredgecolor(val)


    def set_mew(self, val):
        'alias for set_markeredgewidth'
        self.set_markeredgewidth(val)


    def set_mfc(self, val):
        'alias for set_markerfacecolor'
        self.set_markerfacecolor(val)

    def set_mfcalt(self, val):
        'alias for set_markerfacecoloralt'
        self.set_markerfacecoloralt(val)

    def set_ms(self, val):
        'alias for set_markersize'
        self.set_markersize(val)

    def get_aa(self):
        'alias for get_antialiased'
        return self.get_antialiased()

    def get_c(self):
        'alias for get_color'
        return self.get_color()


    def get_ls(self):
        'alias for get_linestyle'
        return self.get_linestyle()


    def get_lw(self):
        'alias for get_linewidth'
        return self.get_linewidth()


    def get_mec(self):
        'alias for get_markeredgecolor'
        return self.get_markeredgecolor()


    def get_mew(self):
        'alias for get_markeredgewidth'
        return self.get_markeredgewidth()


    def get_mfc(self):
        'alias for get_markerfacecolor'
        return self.get_markerfacecolor()

    def get_mfcalt(self, alt=False):
        'alias for get_markerfacecoloralt'
        return self.get_markerfacecoloralt()

    def get_ms(self):
        'alias for get_markersize'
        return self.get_markersize()

    def set_dash_joinstyle(self, s):
        """
        Set the join style for dashed linestyles
        ACCEPTS: ['miter' | 'round' | 'bevel']
        """
        s = s.lower()
        if s not in self.validJoin:
            raise ValueError('set_dash_joinstyle passed "%s";\n' % (s,)
                  + 'valid joinstyles are %s' % (self.validJoin,))
        self._dashjoinstyle = s

    def set_solid_joinstyle(self, s):
        """
        Set the join style for solid linestyles
        ACCEPTS: ['miter' | 'round' | 'bevel']
        """
        s = s.lower()
        if s not in self.validJoin:
            raise ValueError('set_solid_joinstyle passed "%s";\n' % (s,)
                  + 'valid joinstyles are %s' % (self.validJoin,))
        self._solidjoinstyle = s


    def get_dash_joinstyle(self):
        """
        Get the join style for dashed linestyles
        """
        return self._dashjoinstyle

    def get_solid_joinstyle(self):
        """
        Get the join style for solid linestyles
        """
        return self._solidjoinstyle

    def set_dash_capstyle(self, s):
        """
        Set the cap style for dashed linestyles

        ACCEPTS: ['butt' | 'round' | 'projecting']
        """
        s = s.lower()
        if s not in self.validCap:
            raise ValueError('set_dash_capstyle passed "%s";\n' % (s,)
                  + 'valid capstyles are %s' % (self.validCap,))

        self._dashcapstyle = s


    def set_solid_capstyle(self, s):
        """
        Set the cap style for solid linestyles

        ACCEPTS: ['butt' | 'round' |  'projecting']
        """
        s = s.lower()
        if s not in self.validCap:
            raise ValueError('set_solid_capstyle passed "%s";\n' % (s,)
                  + 'valid capstyles are %s' % (self.validCap,))

        self._solidcapstyle = s


    def get_dash_capstyle(self):
        """
        Get the cap style for dashed linestyles
        """
        return self._dashcapstyle


    def get_solid_capstyle(self):
        """
        Get the cap style for solid linestyles
        """
        return self._solidcapstyle


    def is_dashed(self):
        'return True if line is dashstyle'
        return self._linestyle in ('--', '-.', ':')
Exemplo n.º 17
0
    def __init__(
            self,
            xdata,
            ydata,
            linewidth=None,  # all Nones default to rc
            linestyle=None,
            color=None,
            marker=None,
            markersize=None,
            markeredgewidth=None,
            markeredgecolor=None,
            markerfacecolor=None,
            markerfacecoloralt='none',
            fillstyle='full',
            antialiased=None,
            dash_capstyle=None,
            solid_capstyle=None,
            dash_joinstyle=None,
            solid_joinstyle=None,
            pickradius=5,
            drawstyle=None,
            markevery=None,
            **kwargs):
        """
        Create a :class:`~matplotlib.lines.Line2D` instance with *x*
        and *y* data in sequences *xdata*, *ydata*.

        The kwargs are :class:`~matplotlib.lines.Line2D` properties:

        %(Line2D)s

        See :meth:`set_linestyle` for a decription of the line styles,
        :meth:`set_marker` for a description of the markers, and
        :meth:`set_drawstyle` for a description of the draw styles.

        """
        Artist.__init__(self)

        #convert sequences to numpy arrays
        if not iterable(xdata):
            raise RuntimeError('xdata must be a sequence')
        if not iterable(ydata):
            raise RuntimeError('ydata must be a sequence')

        if linewidth is None:
            linewidth = rcParams['lines.linewidth']

        if linestyle is None:
            linestyle = rcParams['lines.linestyle']
        if marker is None:
            marker = rcParams['lines.marker']
        if color is None:
            color = rcParams['lines.color']

        if markersize is None:
            markersize = rcParams['lines.markersize']
        if antialiased is None:
            antialiased = rcParams['lines.antialiased']
        if dash_capstyle is None:
            dash_capstyle = rcParams['lines.dash_capstyle']
        if dash_joinstyle is None:
            dash_joinstyle = rcParams['lines.dash_joinstyle']
        if solid_capstyle is None:
            solid_capstyle = rcParams['lines.solid_capstyle']
        if solid_joinstyle is None:
            solid_joinstyle = rcParams['lines.solid_joinstyle']

        if drawstyle is None:
            drawstyle = 'default'

        self.set_dash_capstyle(dash_capstyle)
        self.set_dash_joinstyle(dash_joinstyle)
        self.set_solid_capstyle(solid_capstyle)
        self.set_solid_joinstyle(solid_joinstyle)

        self.set_linestyle(linestyle)
        self.set_drawstyle(drawstyle)
        self.set_linewidth(linewidth)
        self.set_color(color)
        self._marker = MarkerStyle()
        self.set_marker(marker)
        self.set_markevery(markevery)
        self.set_antialiased(antialiased)
        self.set_markersize(markersize)
        self._dashSeq = None

        self.set_markerfacecolor(markerfacecolor)
        self.set_markerfacecoloralt(markerfacecoloralt)
        self.set_markeredgecolor(markeredgecolor)
        self.set_markeredgewidth(markeredgewidth)
        self.set_fillstyle(fillstyle)

        self.verticalOffset = None

        # update kwargs before updating data to give the caller a
        # chance to init axes (and hence unit support)
        self.update(kwargs)
        self.pickradius = pickradius
        self.ind_offset = 0
        if is_numlike(self._picker):
            self.pickradius = self._picker

        self._xorig = np.asarray([])
        self._yorig = np.asarray([])
        self._invalidx = True
        self._invalidy = True
        self.set_data(xdata, ydata)
Exemplo n.º 18
0
    def __init__(self, xdata, ydata,
                 linewidth=None,  # all Nones default to rc
                 linestyle=None,
                 color=None,
                 marker=None,
                 markersize=None,
                 markeredgewidth=None,
                 markeredgecolor=None,
                 markerfacecolor=None,
                 markerfacecoloralt='none',
                 fillstyle=None,
                 antialiased=None,
                 dash_capstyle=None,
                 solid_capstyle=None,
                 dash_joinstyle=None,
                 solid_joinstyle=None,
                 pickradius=5,
                 drawstyle=None,
                 markevery=None,
                 **kwargs
                 ):
        """
        Create a :class:`~matplotlib.lines.Line2D` instance with *x*
        and *y* data in sequences *xdata*, *ydata*.

        The kwargs are :class:`~matplotlib.lines.Line2D` properties:

        %(Line2D)s

        See :meth:`set_linestyle` for a decription of the line styles,
        :meth:`set_marker` for a description of the markers, and
        :meth:`set_drawstyle` for a description of the draw styles.

        """
        Artist.__init__(self)

        #convert sequences to numpy arrays
        if not iterable(xdata):
            raise RuntimeError('xdata must be a sequence')
        if not iterable(ydata):
            raise RuntimeError('ydata must be a sequence')

        if linewidth is None:
            linewidth = rcParams['lines.linewidth']

        if linestyle is None:
            linestyle = rcParams['lines.linestyle']
        if marker is None:
            marker = rcParams['lines.marker']
        if color is None:
            color = rcParams['lines.color']

        if markersize is None:
            markersize = rcParams['lines.markersize']
        if antialiased is None:
            antialiased = rcParams['lines.antialiased']
        if dash_capstyle is None:
            dash_capstyle = rcParams['lines.dash_capstyle']
        if dash_joinstyle is None:
            dash_joinstyle = rcParams['lines.dash_joinstyle']
        if solid_capstyle is None:
            solid_capstyle = rcParams['lines.solid_capstyle']
        if solid_joinstyle is None:
            solid_joinstyle = rcParams['lines.solid_joinstyle']

        if drawstyle is None:
            drawstyle = 'default'

        self._dashcapstyle = None
        self._dashjoinstyle = None
        self._solidjoinstyle = None
        self._solidcapstyle = None
        self.set_dash_capstyle(dash_capstyle)
        self.set_dash_joinstyle(dash_joinstyle)
        self.set_solid_capstyle(solid_capstyle)
        self.set_solid_joinstyle(solid_joinstyle)

        self._linestyles = None
        self._drawstyle = None
        self._linewidth = None

        self._dashSeq = None
        self._dashOffset = 0

        self.set_linestyle(linestyle)
        self.set_drawstyle(drawstyle)
        self.set_linewidth(linewidth)

        self._color = None
        self.set_color(color)
        self._marker = MarkerStyle()
        self.set_marker(marker)

        self._markevery = None
        self._markersize = None
        self._antialiased = None

        self.set_markevery(markevery)
        self.set_antialiased(antialiased)
        self.set_markersize(markersize)

        self._markeredgecolor = None
        self._markeredgewidth = None
        self._markerfacecolor = None
        self._markerfacecoloralt = None

        self.set_markerfacecolor(markerfacecolor)
        self.set_markerfacecoloralt(markerfacecoloralt)
        self.set_markeredgecolor(markeredgecolor)
        self.set_markeredgewidth(markeredgewidth)

        self.set_fillstyle(fillstyle)

        self.verticalOffset = None

        # update kwargs before updating data to give the caller a
        # chance to init axes (and hence unit support)
        self.update(kwargs)
        self.pickradius = pickradius
        self.ind_offset = 0
        if is_numlike(self._picker):
            self.pickradius = self._picker

        self._xorig = np.asarray([])
        self._yorig = np.asarray([])
        self._invalidx = True
        self._invalidy = True
        self._x = None
        self._y = None
        self._xy = None
        self._path = None
        self._transformed_path = None
        self._subslice = False
        self._x_filled = None  # used in subslicing; only x is needed

        self.set_data(xdata, ydata)
Exemplo n.º 19
0
    def _hack_linedraw(self, line, rotate_marker=None):
        '''
        Modifies the draw method of a :class:`matplotlib.lines.Line2D` object
        to draw different stard and end marker.

        Keyword arguments:

            *line*:
                Line to be modified
                Accepts: Line2D

            *rotate_marker*:
                If set, the end marker will be rotated in direction of their
                corresponding path.
                Accepts: boolean
        '''
        assert isinstance(line, Line2D)

        def new_draw(self_line, renderer):
            def new_draw_markers(self_renderer, gc, marker_path, marker_trans, path, trans, rgbFace=None):
                # get the drawn path for determin the rotation angle
                line_vertices = self_line._get_transformed_path().get_fully_transformed_path().vertices
                vertices = path.vertices

                if len(vertices) == 1:
                    line_set = [[default_marker, vertices]]
                else:
                    if rotate_marker:
                        dx, dy = np.array(line_vertices[-1]) - np.array(line_vertices[-2])
                        end_rot = MarkerStyle(end.get_marker())
                        end_rot._transform += Affine2D().rotate(np.arctan2(dy, dx) - np.pi / 2)
                    else:
                        end_rot = end

                    if len(vertices) == 2:
                        line_set = [[start, vertices[0:1]], [end_rot, vertices[1:2]]]
                    else:
                        line_set = [[start, vertices[0:1]], [default_marker, vertices[1:-1]], [end_rot, vertices[-1:]]]

                for marker, points in line_set:
                    scale = 0.5 if isinstance(marker.get_marker(), np.ndarray) else 1
                    transform = marker.get_transform() + Affine2D().scale(scale * self_line._markersize)
                    old_draw_markers(gc, marker.get_path(), transform, Path(points), trans, rgbFace)

            old_draw_markers = renderer.draw_markers
            renderer.draw_markers = MethodType(new_draw_markers, renderer)
            old_draw(renderer)
            renderer.draw_markers = old_draw_markers

        default_marker = line._marker
        # check if marker is set and visible
        if default_marker:
            start = MarkerStyle(self._get_key("plot.startmarker"))
            if start.get_marker() is None:
                start = default_marker

            end = MarkerStyle(self._get_key("plot.endmarker"))
            if end.get_marker() is None:
                end = default_marker

            if rotate_marker is None:
                rotate_marker = self._get_key("plot.rotatemarker")

            old_draw = line.draw
            line.draw = MethodType(new_draw, line)
            line._markerhacked = True