Domanda

so I am writing three different blocks of text to a figure:

The first I would like to write in bold, large white text:

texttitle = "My Figure"
fig.text(0.8, 0.8, texttitle, color = 'w', visible = True, linespacing = 2, weight = 'bold', size = 'large')

The second in bold, normal white text:

letters = "A:\nB:\nC:"
fig.text(0.8, 0.3, letters, color = 'w', visible = True, linespacing = 2, weight = 'bold')

And the third in normal red text:

numbers = "1\n2\n3"
fig.text(0.9, 0.3, numbers, color = 'r', visible = True, linespacing = 2)

Now I current have to call fig.text() three times in order to get different formatting for the different strings, and therefore I have to specify the location of each string making sure they line up so that I get something like this:

I would like to know is there a way I can do this using just one fig.text() command? Or is there a way I can get the dimensions of the other fig.text() calls such that I can line up the next calls to fig.text()?

I am using Mac OSX with the GTKagg backend.

Thanks, James

È stato utile?

Soluzione

The relevant call is

txt.get_window_extent()

if txt is an Text-object as returned by plt.text.

It is important to draw the figure before getting the extents, as it is not calculated before. An complete example would be:

import matplotlib.pyplot as plt
from matplotlib.transforms import offset_copy

fig = plt.figure()
ax = plt.axes()
txt = plt.text(0.1,0.5,"My text", transform = ax.transAxes)

fig.canvas.draw()

text_bbox = txt.get_window_extent()
transform_for_second_text = offset_copy(ax.transAxes, fig, 
                                        x=text_bbox.width,
                                        units="dots")

plt.text(0.1,0.5, "Second text", transform=transform_for_second_text, color="r")

plt.show()

resulting in:

Output

Please note that fig.canvas.draw() is an quite expensive operation, so don't do this too often, e.g., first create all white texts, then draw the figure canvas, and then create all red texts.

Altri suggerimenti

You might be able to coax such a format by using http://matplotlib.org/users/mathtext.html#mathtext-tutorial

You could then create one long latex string that could have different font sizes, etc... I am not sure if you can also control the color.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top