Python matplotlib.transforms.offset_copy() Examples

The following are 7 code examples of matplotlib.transforms.offset_copy(). 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.transforms , or try the search function .
Example #1
Source File: mpl_finance_ext.py    From Stock-Price-Prediction-With-Indicators with MIT License 6 votes vote down vote up
def _add_text_box(fig, axis, text, x_p, y_p):
    x = axis.get_xlim()
    y = axis.get_ylim()
    text_x = x[0] / 100 * x_p
    text_y = y[1] / 100 * y_p

    trans_offset = mtrans.offset_copy(
        axis.transData,
        fig=fig,
        x=0.0,
        y=0.0,
        units='inches'
    )

    axis.text(text_x, text_y, text, ha='left', va='center',
              transform=trans_offset, color='#535353',
              bbox=dict(alpha=0.4, color=label_colors)) 
Example #2
Source File: demo_agg_filter.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def drop_shadow_line(ax):
    # copied from examples/misc/svg_filter_line.py

    # draw lines
    l1, = ax.plot([0.1, 0.5, 0.9], [0.1, 0.9, 0.5], "bo-",
                  mec="b", mfc="w", lw=5, mew=3, ms=10, label="Line 1")
    l2, = ax.plot([0.1, 0.5, 0.9], [0.5, 0.2, 0.7], "ro-",
                  mec="r", mfc="w", lw=5, mew=3, ms=10, label="Line 1")

    gauss = DropShadowFilter(4)

    for l in [l1, l2]:

        # draw shadows with same lines with slight offset.

        xx = l.get_xdata()
        yy = l.get_ydata()
        shadow, = ax.plot(xx, yy)
        shadow.update_from(l)

        # offset transform
        ot = mtransforms.offset_copy(l.get_transform(), ax.figure,
                                     x=4.0, y=-6.0, units='points')

        shadow.set_transform(ot)

        # adjust zorder of the shadow lines so that it is drawn below the
        # original lines
        shadow.set_zorder(l.get_zorder() - 0.5)
        shadow.set_agg_filter(gauss)
        shadow.set_rasterized(True)  # to support mixed-mode renderers

    ax.set_xlim(0., 1.)
    ax.set_ylim(0., 1.)

    ax.xaxis.set_visible(False)
    ax.yaxis.set_visible(False) 
Example #3
Source File: rainbow_text.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def rainbow_text(x, y, strings, colors, ax=None, **kw):
    """
    Take a list of ``strings`` and ``colors`` and place them next to each
    other, with text strings[i] being shown in colors[i].

    This example shows how to do both vertical and horizontal text, and will
    pass all keyword arguments to plt.text, so you can set the font size,
    family, etc.

    The text will get added to the ``ax`` axes, if provided, otherwise the
    currently active axes will be used.
    """
    if ax is None:
        ax = plt.gca()
    t = ax.transData
    canvas = ax.figure.canvas

    # horizontal version
    for s, c in zip(strings, colors):
        text = ax.text(x, y, s + " ", color=c, transform=t, **kw)
        text.draw(canvas.get_renderer())
        ex = text.get_window_extent()
        t = transforms.offset_copy(
            text.get_transform(), x=ex.width, units='dots')

    # vertical version
    for s, c in zip(strings, colors):
        text = ax.text(x, y, s + " ", color=c, transform=t,
                       rotation=90, va='bottom', ha='center', **kw)
        text.draw(canvas.get_renderer())
        ex = text.get_window_extent()
        t = transforms.offset_copy(
            text.get_transform(), y=ex.height, units='dots') 
Example #4
Source File: mixins.py    From traffic with MIT License 5 votes vote down vote up
def plot(
        self, ax: Axes, text_kw=None, shift=None, **kwargs
    ) -> List[Artist]:  # coverage: ignore

        if shift is None:
            # flake B006
            shift = dict(units="dots", x=15)

        if text_kw is None:
            text_kw = {}
        else:
            # since we may modify it, let's make a copy
            text_kw = {**text_kw}

        if "projection" in ax.__dict__ and "transform" not in kwargs:
            from cartopy.crs import PlateCarree
            from matplotlib.transforms import offset_copy

            kwargs["transform"] = PlateCarree()
            geodetic_transform = PlateCarree()._as_mpl_transform(ax)
            text_kw["transform"] = offset_copy(geodetic_transform, **shift)

        if "color" not in kwargs:
            kwargs["color"] = "black"

        if "s" not in text_kw:
            if hasattr(self, "callsign"):
                text_kw["s"] = getattr(self, "callsign")  # noqa: B009
            if hasattr(self, "name"):
                text_kw["s"] = getattr(self, "name")  # noqa: B009

        cumul: List[Artist] = []
        cumul.append(ax.scatter(self.longitude, self.latitude, **kwargs))

        west, east, south, north = ax.get_extent(PlateCarree())
        if west <= self.longitude <= east and south <= self.latitude <= north:
            cumul.append(ax.text(self.longitude, self.latitude, **text_kw))

        return cumul 
Example #5
Source File: mpl_finance_ext.py    From Stock-Price-Prediction-With-Indicators with MIT License 5 votes vote down vote up
def add_price_flag(fig, axis, series, color, last_index=None):
    """
    Add a price flag at the end of the data
    series in the chart
    :param fig: Figure
    :param axis: Axis
    :param series: Pandas Series
    :param color: Color of the flag
    :param last_index: Last index
    """

    series = series.dropna()
    value = series.tail(1)

    index = value.index.tolist()[0]
    if last_index is not None:
        axis.plot(
            [index, last_index], [value.values[0], value.values[0]],
            color=color, linewidth=0.6, linestyle='--', alpha=0.6
        )
    else:
        last_index = index

    trans_offset = mtrans.offset_copy(
        axis.transData, fig=fig,
        x=0.05, y=0.0, units='inches'
    )

    # Add price text box for candlestick
    value_clean = format(value.values[0], '.6f')
    axis.text(
        last_index, value.values, value_clean,
        size=7, va="center", ha="left",
        transform=trans_offset,
        color='white',
        bbox=dict(
            boxstyle="angled,pad=0.2",
            alpha=0.6, color=color
        )
    ) 
Example #6
Source File: pyseqlogo.py    From pyseqlogo with MIT License 4 votes vote down vote up
def _draw_text_data_coord(height_matrix,
                          ax,
                          fontfamily,
                          colorscheme='classic',
                          scalex=1,
                          draw_axis=False,
                          debug=False):
    fig = ax.get_figure()
    bbox = ax.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
    width, height = bbox.width, bbox.height
    width *= fig.dpi
    height *= fig.dpi
    fontsize = (height / 1.7) * 72.0 / fig.dpi  #/72.0
    font = _setup_font(fontsize=fontsize, fontfamily=fontfamily)
    trans_offset = transforms.offset_copy(
        ax.transData, fig=fig, x=1, y=0, units='points')
    if not isinstance(colorscheme, dict):
        colorscheme = default_colorschemes[colorscheme]

    for xindex, xcol in enumerate(height_matrix):
        yshift = 0
        total_shift = 0
        total_score = 0
        for basechar, basescore in xcol:
            txt = ax.text(
                xindex + 1,
                0,
                basechar,
                transform=trans_offset,
                fontsize=fontsize,
                color=colorscheme[basechar],
                ha='center',
                va='baseline',
                family='monospace',
                #va='baseline',
                fontproperties=font, )
            txt.set_path_effects([Scale(1.0, basescore)])
            fig.canvas.draw()
            window_ext = txt.get_window_extent(
                txt._renderer)  #(fig.canvas.renderer) #txt._renderer)
            if basescore > 0.3:
                yshift = window_ext.height * basescore  #- fontsize/10# fontsize/4#/1.20 #*.85 #* fig.dpi/72.0
            else:
                yshift = window_ext.height * basescore  # - fontsize/11# fontsize/4#/1.20 #*.85 #* fig.dpi/72.0

            total_score += basescore

            if debug:
                ax.axhline(
                    y=total_score, color='r', linstyle='dashed', linewidth=1)
            trans_offset = transforms.offset_copy(
                txt._transform, fig=fig, y=yshift, units='dots')
        trans_offset = transforms.offset_copy(
            ax.transData, fig=fig, x=1, y=0, units='dots')
    if not draw_axis:
        ax.axis('off') 
Example #7
Source File: Map_Plot.py    From MesoPy with MIT License 4 votes vote down vote up
def main():

    # This is just useful for formatting returned dict
    # pp = pprint.PrettyPrinter(indent=2)

    # Create instance of Meso object, pass in YOUR token
    m = Meso(token='YOUR TOKEN')

    # Use to lookup stations, could specify counties or whatever here
    # findstationids = m.station_list(state='CO')
    # print(findstationids)

    # Grab most recent temp (F) ob in last 90 min at each of the below stations
    stations = ['kgxy, kccu, kcos, kden, kgjt, kbdu, kpub, klhx, kspd, kdro, ksbs, keeo, kguc, klic, '
                'kstk, kals, ktad']
    latest = m.latest(stid=stations, within='90', vars='air_temp', units='temp|F')

    # create a list to store everything, iterate over the number of objs returned in latest and append
    # lat, long, temp, and stid for use later
    data = []
    [data.append((float(ob['LATITUDE']), float(ob['LONGITUDE']), float(ob['OBSERVATIONS']['air_temp_value_1']['value']),
                  ob['STID'])) for ob in latest['STATION']]
    print(data)

    # Create a MapQuest open aerial instance.
    map_quest_aerial = cimgt.MapQuestOpenAerial()
    # Create a GeoAxes in the tile's projection.
    ax = plt.axes(projection=map_quest_aerial.crs)
    # Limit the extent of the map to Colorado's borders
    ax.set_extent([-102.03, -109.03, 37, 41])
    # Add the MapQuest data at zoom level 8.
    ax.add_image(map_quest_aerial, 8)

    # Plot lat/long pts with below params
    for lat, lon, temp, stid in data:
        plt.plot(lon, lat, marker='o', color='y', markersize=1,
                 alpha=0.7, transform=ccrs.Geodetic())

    # Transforms for the text func we're about to call
    geodetic_transform = ccrs.Geodetic()._as_mpl_transform(ax)
    text_transform = offset_copy(geodetic_transform, units='dots', x=0, y=0)

    # Plot temp and station id for each of the markers
    for lat, lon, temp, stid in data:
        plt.text(lon, lat, stid + '\n' + str(round(temp, 1)) + u' \N{DEGREE SIGN}' + 'F',
                 verticalalignment='center', horizontalalignment='center',
                 transform=text_transform, fontsize=9,
                 bbox=dict(facecolor='wheat', alpha=0.5, boxstyle='round'))
    plt.title('Current Weather Around Colorado')
    plt.show()