Python matplotlib.lines.Line2D() Examples

The following are 30 code examples of matplotlib.lines.Line2D(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module matplotlib.lines , or try the search function .
Example #1
Source File: arts_lookup.py    From typhon with MIT License 10 votes vote down vote up
def _add_opacity_legend(ax=None):
    """Add legend to an opacity lookup table plot."""
    if ax is None:
        ax = plt.gca()

    blue_line = Line2D([], [], label='species opacity')
    black_line = Line2D([], [], color='k', linewidth=1.,
                        label='total opacity')
    dashed_line = Line2D([], [], color='k', linestyle='--',
                         linewidth=1., label='opacity=1')

    handles = [blue_line, black_line, dashed_line]
    labels = [h.get_label() for h in handles]

    ax.legend(handles=handles, labels=labels, fontsize='xx-small',
              loc='upper left', ncol=6) 
Example #2
Source File: plot_name.py    From pyhanlp with Apache License 2.0 8 votes vote down vote up
def newline(p1, p2, color=None, marker=None):
    """
    https://stackoverflow.com/questions/36470343/how-to-draw-a-line-with-matplotlib
    :param p1:
    :param p2:
    :return:
    """
    ax = plt.gca()
    xmin, xmax = ax.get_xbound()

    if (p2[0] == p1[0]):
        xmin = xmax = p1[0]
        ymin, ymax = ax.get_ybound()
    else:
        ymax = p1[1] + (p2[1] - p1[1]) / (p2[0] - p1[0]) * (xmax - p1[0])
        ymin = p1[1] + (p2[1] - p1[1]) / (p2[0] - p1[0]) * (xmin - p1[0])

    l = mlines.Line2D([xmin, xmax], [ymin, ymax], color=color, marker=marker)
    ax.add_line(l)
    return l 
Example #3
Source File: blocking_input.py    From Computable with MIT License 6 votes vote down vote up
def add_click(self, event):
        """
        This add the coordinates of an event to the list of clicks
        """
        self.clicks.append((event.xdata, event.ydata))

        verbose.report("input %i: %f,%f" %
                       (len(self.clicks), event.xdata, event.ydata))

        # If desired plot up click
        if self.show_clicks:
            line = mlines.Line2D([event.xdata], [event.ydata],
                                 marker='+', color='r')
            event.inaxes.add_line(line)
            self.marks.append(line)
            self.fig.canvas.draw() 
Example #4
Source File: _base.py    From Mastering-Elasticsearch-7.0 with MIT License 6 votes vote down vote up
def _gen_axes_spines(self, locations=None, offset=0.0, units='inches'):
        """
        Returns
        -------
        dict
            Mapping of spine names to `Line2D` or `Patch` instances that are
            used to draw axes spines.

            In the standard axes, spines are single line segments, but in other
            projections they may not be.

        Notes
        -----
        Intended to be overridden by new projection types.
        """
        return OrderedDict((side, mspines.Spine.linear_spine(self, side))
                           for side in ['left', 'right', 'bottom', 'top']) 
Example #5
Source File: graphs.py    From king-phisher with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def add_legend_patch(self, legend_rows, fontsize=None):
		if matplotlib.__version__ == '3.0.2':
			self.logger.warning('skipping legend patch with matplotlib v3.0.2 for compatibility')
			return
		if self._legend is not None:
			self._legend.remove()
			self._legend = None
		legend_bbox = self.figure.legend(
			tuple(lines.Line2D([], [], color=patch_color, lw=3, ls=style) for patch_color, style, _ in legend_rows),
			tuple(label for _, _, label in legend_rows),
			borderaxespad=1,
			columnspacing=1.5,
			fontsize=self.fontsize_scale,
			ncol=3,
			frameon=True,
			handlelength=2,
			handletextpad=0.5,
			labelspacing=0.5,
			loc='upper right'
		)
		legend_bbox.get_frame().set_facecolor(self.get_color('line_bg', ColorHexCode.GRAY))
		for text in legend_bbox.get_texts():
			text.set_color('white')
		legend_bbox.legendPatch.set_linewidth(0)
		self._legend = legend_bbox 
Example #6
Source File: blocking_input.py    From matplotlib-4-abaqus with MIT License 6 votes vote down vote up
def add_click(self, event):
        """
        This add the coordinates of an event to the list of clicks
        """
        self.clicks.append((event.xdata, event.ydata))

        verbose.report("input %i: %f,%f" %
                       (len(self.clicks), event.xdata, event.ydata))

        # If desired plot up click
        if self.show_clicks:
            line = mlines.Line2D([event.xdata], [event.ydata],
                                 marker='+', color='r')
            event.inaxes.add_line(line)
            self.marks.append(line)
            self.fig.canvas.draw() 
Example #7
Source File: arts_lookup.py    From typhon with MIT License 6 votes vote down vote up
def _add_xsec_legend(lookup, ipressures, ax=None):
    """Add legend to a cross section lookup table plot."""
    if ax is None:
        ax = plt.gca()

    pgrid = lookup.pressuregrid
    colors = [plt.cm.viridis(i) for i in np.linspace(0, 1, len(ipressures))]
    handles = [Line2D([], [],
                      color=colors[i],
                      label=f'{pgrid[ip]/100.:8.3f} hPa')
               for i, ip in enumerate(ipressures)]

    labels = [h.get_label() for h in handles]

    ax.legend(handles=handles, labels=labels, fontsize='xx-small',
              loc='upper left', ncol=6) 
Example #8
Source File: mplCanvas.py    From 3DGCN with MIT License 6 votes vote down vote up
def addCanvasDashedWedge(self, p1, p2, p3, dash=(2, 2), color=(0, 0, 0), color2=None, **kwargs):
        canvas = self._axes
        dash = (3, 3)
        pts1 = self._getLinePoints(p1, p2, dash)
        pts2 = self._getLinePoints(p1, p3, dash)
        pts1 = [self.rescalePt(p) for p in pts1]
        pts2 = [self.rescalePt(p) for p in pts2]
        if len(pts2) < len(pts1):
            pts2, pts1 = pts1, pts2
        for i in range(len(pts1)):
            if color2 and color2 != color:
                mp = (pts1[i][0] + pts2[i][0]) / 2., (pts1[i][1] + pts2[i][1]) / 2.
                canvas.add_line(Line2D((pts1[i][0], mp[0]), (pts1[i][1], mp[1]), color=color, **kwargs))
                canvas.add_line(Line2D((mp[0], pts2[i][0]), (mp[1], pts2[i][1]), color=color2, **kwargs))
            else:
                canvas.add_line(
                    Line2D((pts1[i][0], pts2[i][0]), (pts1[i][1], pts2[i][1]), color=color, **kwargs)) 
Example #9
Source File: axis.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
def _get_tick1line(self):
        'Get the default line2D instance'
        # x in data coords, y in axes coords
        l = mlines.Line2D(xdata=(0,), ydata=(0,), color=self._color,
                          linestyle='None', marker=self._tickmarkers[0],
                          markersize=self._size,
                          markeredgewidth=self._width, zorder=self._zorder)
        l.set_transform(self.axes.get_xaxis_transform(which='tick1'))
        self._set_artist_props(l)
        return l 
Example #10
Source File: legend.py    From matplotlib-4-abaqus with MIT License 5 votes vote down vote up
def get_lines(self):
        'return a list of lines.Line2D instances in the legend'
        return [h for h in self.legendHandles if isinstance(h, Line2D)] 
Example #11
Source File: axis.py    From matplotlib-4-abaqus with MIT License 5 votes vote down vote up
def get_majorticklines(self):
        'Return the major tick lines as a list of Line2D instances'
        lines = []
        ticks = self.get_major_ticks()
        for tick in ticks:
            lines.append(tick.tick1line)
            lines.append(tick.tick2line)
        return cbook.silent_list('Line2D ticklines', lines) 
Example #12
Source File: axis.py    From matplotlib-4-abaqus with MIT License 5 votes vote down vote up
def _get_gridline(self):
        'Get the default line2D instance'
        # x in axes coords, y in data coords
        l = mlines.Line2D(xdata=(0, 1), ydata=(0, 0),
                    color=rcParams['grid.color'],
                    linestyle=rcParams['grid.linestyle'],
                    linewidth=rcParams['grid.linewidth'],
                    alpha=rcParams['grid.alpha'],
                    markersize=0
                    )

        l.set_transform(self.axes.get_yaxis_transform(which='grid'))
        l.get_path()._interpolation_steps = GRIDLINE_INTERPOLATION_STEPS
        self._set_artist_props(l)
        return l 
Example #13
Source File: axis.py    From matplotlib-4-abaqus with MIT License 5 votes vote down vote up
def _get_tick2line(self):
        'Get the default line2D instance'
        # x in axes coords, y in data coords
        l = mlines.Line2D((1,), (0,),
                    color=self._color,
                    marker=self._tickmarkers[1],
                    linestyle='None',
                    markersize=self._size,
                    markeredgewidth=self._width,
                    zorder=self._zorder,
                    )
        l.set_transform(self.axes.get_yaxis_transform(which='tick2'))
        self._set_artist_props(l)
        return l 
Example #14
Source File: axis.py    From matplotlib-4-abaqus with MIT License 5 votes vote down vote up
def _get_tick1line(self):
        'Get the default line2D instance'
        # x in axes coords, y in data coords

        l = mlines.Line2D((0,), (0,),
                    color=self._color,
                    marker=self._tickmarkers[0],
                    linestyle='None',
                    markersize=self._size,
                    markeredgewidth=self._width,
                    zorder=self._zorder,
                    )
        l.set_transform(self.axes.get_yaxis_transform(which='tick1'))
        self._set_artist_props(l)
        return l 
Example #15
Source File: axis.py    From matplotlib-4-abaqus with MIT License 5 votes vote down vote up
def get_minorticklines(self):
        'Return the minor tick lines as a list of Line2D instances'
        lines = []
        ticks = self.get_minor_ticks()
        for tick in ticks:
            lines.append(tick.tick1line)
            lines.append(tick.tick2line)
        return cbook.silent_list('Line2D ticklines', lines) 
Example #16
Source File: _base.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
def get_ygridlines(self):
        """Get the y grid lines as a list of `Line2D` instances."""
        return cbook.silent_list('Line2D ygridline',
                                 self.yaxis.get_gridlines()) 
Example #17
Source File: _base.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
def get_xticklines(self):
        """Get the x tick lines as a list of `Line2D` instances."""
        return cbook.silent_list('Line2D xtickline',
                                 self.xaxis.get_ticklines()) 
Example #18
Source File: _base.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
def get_lines(self):
        """Return a list of lines contained by the Axes"""
        return cbook.silent_list('Line2D', self.lines) 
Example #19
Source File: pyplot.py    From matplotlib-4-abaqus with MIT License 5 votes vote down vote up
def figlegend(handles, labels, loc, **kwargs):
    """
    Place a legend in the figure.

    *labels*
      a sequence of strings

    *handles*
      a sequence of :class:`~matplotlib.lines.Line2D` or
      :class:`~matplotlib.patches.Patch` instances

    *loc*
      can be a string or an integer specifying the legend
      location

    A :class:`matplotlib.legend.Legend` instance is returned.

    Example::

      figlegend( (line1, line2, line3),
                 ('label1', 'label2', 'label3'),
                 'upper right' )

    .. seealso::

       :func:`~matplotlib.pyplot.legend`

    """
    l = gcf().legend(handles, labels, loc, **kwargs)
    draw_if_interactive()
    return l


## Figure and Axes hybrid ## 
Example #20
Source File: _base.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
def _makeline(self, x, y, kw, kwargs):
        kw = {**kw, **kwargs}  # Don't modify the original kw.
        default_dict = self._getdefaults(set(), kw)
        self._setdefaults(default_dict, kw)
        seg = mlines.Line2D(x, y, **kw)
        return seg 
Example #21
Source File: _base.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
def _xy_from_xy(self, x, y):
        if self.axes.xaxis is not None and self.axes.yaxis is not None:
            bx = self.axes.xaxis.update_units(x)
            by = self.axes.yaxis.update_units(y)

            if self.command != 'plot':
                # the Line2D class can handle unitized data, with
                # support for post hoc unit changes etc.  Other mpl
                # artists, e.g., Polygon which _process_plot_var_args
                # also serves on calls to fill, cannot.  So this is a
                # hack to say: if you are not "plot", which is
                # creating Line2D, then convert the data now to
                # floats.  If you are plot, pass the raw data through
                # to Line2D which will handle the conversion.  So
                # polygons will not support post hoc conversions of
                # the unit type since they are not storing the orig
                # data.  Hopefully we can rationalize this at a later
                # date - JDH
                if bx:
                    x = self.axes.convert_xunits(x)
                if by:
                    y = self.axes.convert_yunits(y)

        # like asanyarray, but converts scalar to array, and doesn't change
        # existing compatible sequences
        x = _check_1d(x)
        y = _check_1d(y)
        if x.shape[0] != y.shape[0]:
            raise ValueError("x and y must have same first dimension, but "
                             "have shapes {} and {}".format(x.shape, y.shape))
        if x.ndim > 2 or y.ndim > 2:
            raise ValueError("x and y can be no greater than 2-D, but have "
                             "shapes {} and {}".format(x.shape, y.shape))

        if x.ndim == 1:
            x = x[:, np.newaxis]
        if y.ndim == 1:
            y = y[:, np.newaxis]
        return x, y 
Example #22
Source File: legend.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
def get_lines(self):
        'Return a list of `~.lines.Line2D` instances in the legend.'
        return [h for h in self.legendHandles if isinstance(h, Line2D)] 
Example #23
Source File: axis.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
def get_ticklines(self, minor=False):
        'Return the tick lines as a list of Line2D instances'
        if minor:
            return self.get_minorticklines()
        return self.get_majorticklines() 
Example #24
Source File: axis.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
def get_minorticklines(self):
        'Return the minor tick lines as a list of Line2D instances'
        lines = []
        ticks = self.get_minor_ticks()
        for tick in ticks:
            lines.append(tick.tick1line)
            lines.append(tick.tick2line)
        return cbook.silent_list('Line2D ticklines', lines) 
Example #25
Source File: axis.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
def get_gridlines(self):
        'Return the grid lines as a list of Line2D instance'
        ticks = self.get_major_ticks()
        return cbook.silent_list('Line2D gridline',
                                 [tick.gridline for tick in ticks]) 
Example #26
Source File: axis.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
def _get_gridline(self):
        'Get the default line2D instance'
        # x in axes coords, y in data coords
        l = mlines.Line2D(xdata=(0, 1), ydata=(0, 0),
                          color=self._grid_color,
                          linestyle=self._grid_linestyle,
                          linewidth=self._grid_linewidth,
                          alpha=self._grid_alpha,
                          markersize=0,
                          **self._grid_kw)
        l.set_transform(self.axes.get_yaxis_transform(which='grid'))
        l.get_path()._interpolation_steps = GRIDLINE_INTERPOLATION_STEPS
        self._set_artist_props(l)
        return l 
Example #27
Source File: axis.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
def _get_tick2line(self):
        'Get the default line2D instance'
        # x in axes coords, y in data coords
        l = mlines.Line2D((1,), (0,),
                          color=self._color,
                          marker=self._tickmarkers[1],
                          linestyle='None',
                          markersize=self._size,
                          markeredgewidth=self._width,
                          zorder=self._zorder)
        l.set_transform(self.axes.get_yaxis_transform(which='tick2'))
        self._set_artist_props(l)
        return l 
Example #28
Source File: axis.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
def _get_tick1line(self):
        'Get the default line2D instance'
        # x in axes coords, y in data coords

        l = mlines.Line2D((0,), (0,),
                          color=self._color,
                          marker=self._tickmarkers[0],
                          linestyle='None',
                          markersize=self._size,
                          markeredgewidth=self._width,
                          zorder=self._zorder)
        l.set_transform(self.axes.get_yaxis_transform(which='tick1'))
        self._set_artist_props(l)
        return l 
Example #29
Source File: axis.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
def _get_gridline(self):
        'Get the default line2D instance'
        # x in data coords, y in axes coords
        l = mlines.Line2D(xdata=(0.0, 0.0), ydata=(0, 1.0),
                          color=self._grid_color,
                          linestyle=self._grid_linestyle,
                          linewidth=self._grid_linewidth,
                          alpha=self._grid_alpha,
                          markersize=0,
                          **self._grid_kw)
        l.set_transform(self.axes.get_xaxis_transform(which='grid'))
        l.get_path()._interpolation_steps = GRIDLINE_INTERPOLATION_STEPS
        self._set_artist_props(l)

        return l 
Example #30
Source File: mplCanvas.py    From 3DGCN with MIT License 5 votes vote down vote up
def addCanvasLine(self, p1, p2, color=(0, 0, 0), color2=None, **kwargs):
        canvas = self._axes
        p1 = self.rescalePt(p1)
        p2 = self.rescalePt(p2)
        if color2 and color2 != color:
            mp = (p1[0] + p2[0]) / 2., (p1[1] + p2[1]) / 2.
            canvas.add_line(Line2D((p1[0], mp[0]), (p1[1], mp[1]), color=color, **kwargs))
            canvas.add_line(Line2D((mp[0], p2[0]), (mp[1], p2[1]), color=color2, **kwargs))
        else:
            canvas.add_line(Line2D((p1[0], p2[0]), (p1[1], p2[1]), color=color, **kwargs))