1

How can I make only part of the text in an annotation box transparent?

As an example, this code (adapted from here)

import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)

t = np.arange(0.0, 5.0, 0.01)
s = np.cos(2*np.pi*t)
line, = ax.plot(t, s, lw=2)

ax.annotate('local max (transparent)', xy=(2, 1), xytext=(3, 1.5),
            arrowprops=dict(facecolor='black', shrink=0.05),
            )

ax.set_ylim(-2,2)
plt.show()

produces the following output:

enter image description here

I would like the word transparent in the annotation box to be slightly transparent. However, the rest of the text (local maximum) should be displayed as it currently is.

ignoring_gravity
  • 6,677
  • 4
  • 32
  • 65
  • 1
    By default all text is opaque. What exactly do you want to achieve? Presumably the word *opaque* has a different meaning for you then for everyone else, so maybe just explain the desired output without using this word? – ImportanceOfBeingErnest May 03 '18 at 15:56
  • Sorry, I thought 'opaque' meant the opposite of what it does. I would like the text to be transparent – ignoring_gravity May 03 '18 at 16:02
  • On my plot, there are two kinds of lines: ones drawn with alpha=1, and ones drawn with alpha=.3. The latter appear slightly transparent compared to the former - I would like something similar to happen with the text in my annotation box. – ignoring_gravity May 03 '18 at 16:06
  • 1
    Hehe, ok, now it makes sense. ;-) Unfortunately there is no easy solution to this, because the text always as unique properties. So the workaround would be to use the methods shown in [this question](https://stackoverflow.com/questions/9169052/partial-coloring-of-text-in-matplotlib). – ImportanceOfBeingErnest May 03 '18 at 17:46

1 Answers1

1

You can use the alpha parameter. You can also use alpha inside arrowprops parameter dict to make the arrow transparent as well.

ax.annotate('local max (transparent)', xy=(2, 1), xytext=(3, 1.5),
        arrowprops=dict(facecolor='black', shrink=0.05,alpha=0.5),
        alpha=0.5
        )

It will produce the following plot:

Plot