0

I'm plotting some text in a figure with ax.text() method, of matplotlib. Nevertheless, if the string var contains underscores, this are understood as subindixes.

Is this a bug to report? Or am I doing something wrong. I have already tried with '\033[3m' characters, but no italic letter show up. Since not all the text goes in italic, I cannot change rc.Params.

Any aid is appreciated.

import matplotlib.pyplot as plt
fig, ax = plt.subplots()
var = 'Hello_12'
text = f"Dataset: ${var}$"
ax.text(0.5,0.5, text)

enter image description here

Miguel Gonzalez
  • 706
  • 7
  • 20
  • What are you trying to achieve? Do you want the underscores to be preserved literally? And do you want to get italic text? – mkrieger1 Sep 27 '21 at 14:39
  • 2
    Do you know, that the dollars "$" do not only make the text in italics, but enters the Latex math environment? There, you can escape the underscore with "\_". The problem is, that numbers are not in italics in this math environment. There should however be another way to get italic text in matplotlib – Libavius Sep 27 '21 at 14:43
  • That's it, I want to keep the underscorse and turn 'var' content into italic text. Thanks for the input @Libavius, I didn't know. I'd like to turn numbers into italic too, so maybe Latex is not the way, isn't it? – Miguel Gonzalez Sep 27 '21 at 14:56

1 Answers1

1

To get the text to be italic, you could provide the style keyword argument to the Axes.text method:

var = 'Hello_12'
text = f"Dataset: {var}"
ax.text(0.5,0.5, text, style='italic')

By doing it in this way, you don't need to use TeX formatting. Hence, the underscore will be preserved instead of interpreting the character after the underscore to be a subscript.

Edit

After the comment of @Miguel Gonzalez, I propose the following solution. Note however that this does require you to have a LaTeX installation.

Consider the code below:

var = 'Hello\_12'
text = r"Dataset: $\mathit{" + var + "}$"
ax.text(0.5,0.5, text, usetex=True)

First of all, the _ character in var must be escaped using a \ . Secondly, we want to use \mathit to get italic text in math modus. Note that I declared this as a raw string (r"...") to prevent additional escape characters. Lastly, we supply the usetex keyword argument with a value True to the Axes.text method. This will produce the following output: output italic text

DeX97
  • 637
  • 3
  • 12