Skip to content

[Doc]: Rewrite rainbow_text example to use annotate() #25941

Closed

Description

@anntzer

Documentation Link

https://matplotlib.org/stable/gallery/text_labels_and_annotations/rainbow_text.html

Problem

As noted in #25907 (comment), the rainbow_text example can likely be rewritten in a simpler fashion using annotate(), similarly to #25905, more simply than with explicit offset_copies.

Suggested improvement

Rewrite the example using annotate().

Activity

  1. niranjank2022 commented on May 21, 2023

    @niranjank2022
    Contributor

    I would like to work on this. Please assign me this task.

  2. niranjank2022 commented on May 21, 2023

    @niranjank2022
    Contributor

    I went through the Contributing Guidelines, it is mentioned that we can create PR and work on it. But, I have a doubt, which branch should I have to use for PR? Please help!

  3. rcomer commented on May 21, 2023

    @rcomer
    Member

    Thanks for your interest in contributing @niranjank2022! You should create a new branch to make the change. We have some workflow guidance here:
    https://matplotlib.org/devdocs/devel/development_workflow.html

  4. niranjank2022 commented on May 21, 2023

    @niranjank2022
    Contributor

    Thank you. I will create a PR once I finish my changes, by tomorrow._

  5. niranjank2022 commented on May 23, 2023

    @niranjank2022
    Contributor

    One doubt!
    We need plt.artist.Artist object to position each word next to each other, right?

  6. Mubin17 commented on May 26, 2023

    @Mubin17
    Contributor
    import matplotlib.pyplot as plt
    
    def rainbow_text(x, y, strings, colors, orientation='horizontal',
                     ax=None, **kwargs):
        """
        Take a list of *strings* and *colors* and place them next to each
        other, with text strings[i] being shown in colors[i].
    
        Parameters
        ----------
        x, y : float
            Text position in data coordinates.
        strings : list of str
            The strings to draw.
        colors : list of color
            The colors to use.
        orientation : {'horizontal', 'vertical'}
        ax : Axes, optional
            The Axes to draw into. If None, the current axes will be used.
        **kwargs
            All other keyword arguments are passed to plt.annotate(), so you can
            set the font size, family, etc.
        """
        if ax is None:
            ax = plt.gca()
        
        assert orientation in ['horizontal', 'vertical']
        if orientation == 'vertical':
            kwargs.update(rotation=90, verticalalignment='bottom')
        
        for s, c in zip(strings, colors):
            ax.annotate(s + " ", (x, y), color=c, **kwargs)
            if orientation == 'horizontal':
                x += 0.1
            else:
                y += 0.1
    
    words = "all unicorns poop rainbows ! ! !".split()
    colors = ['red', 'orange', 'gold', 'lawngreen', 'lightseagreen', 'royalblue',
              'blueviolet']
    plt.figure(figsize=(6, 6), dpi=100)
    rainbow_text(0.1, 0.05, words, colors, size=18)
    rainbow_text(0.05, 0.1, words, colors, orientation='vertical', size=18)
    plt.show()
    Screenshot 2023-05-26 at 12 22 40 AM

    @anntzer The code above is my attempt to rewrite rainbow_text simpler fashion using annotate(), however, I am having an issue formatting text appropriately within the figure. Do have any suggestions on how can I fix that? Thanks

  7. anntzer commented on May 26, 2023

    @anntzer
    ContributorAuthor

    I don't have the actual implementation written, figuring that out is the point of the issue.

  8. timhoffm commented on May 26, 2023

    @timhoffm
    Member

    @anntzer On a completely different note, and since decomposing text position is hard: Would it be possible/interesting to render the text in black, extract that from the canvas as pixel image. Recolor the pixel image with a continuos gradient and write it back? - Of course, this is quite hacky, but so is the word decomposition.

  9. anntzer commented on May 27, 2023

    @anntzer
    ContributorAuthor

    since decomposing text position is hard

    Really not so much. The implementation is basically

    from pylab import *
    
    t0 = text(.1, .1, "hello", c="C0")
    t1 = annotate(
        "world",
        xy=(1, 0), xycoords=t0,  # Immediately to the left of t0.
        xytext=(.5, 0), textcoords="offset fontsize",  # Shifted by half a fontsize (for spacing).
        va="bottom", c="C1")
    ...
    show()

    One just needs to wrap this in a proper loop over the words and figure out the correct alignment flags for the vertical case.

    Recolor the pixel image with a continuos gradient and write it back?

    That's more or less already showcased at https://matplotlib.org/stable/gallery/text_labels_and_annotations/demo_text_path.html.

  10. timhoffm commented on May 27, 2023

    @timhoffm
    Member

    That's more or less already showcased

    👍

    Isn‘t that enough then? A rainbow-by-word coloring doesn’t seem too useful. Maybe replace this example by one that colors single words in a text? (I assume that would also need the proposed annotate pattern)

  11. anntzer commented on May 27, 2023

    @anntzer
    ContributorAuthor

    I agree the rainbow-by-word example is not really useful in itself indeed (except for the fact that it produces selectable text in pdf output, which is a slightly niche requirement for the usecase here), but demo-ing positioning-relative-to-another artist (as in the implementation I suggest) is nice (IMO).
    Perhaps this example could just include both approaches.

  12. added this to the v3.8.0 milestone on Jun 5, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions