con
con

Reputation: 6123

Italicizing letters and numbers in matplotlib

I am attempting to italicize text in my plot:

import matplotlib.pyplot as plt

plt.plot([1,2,3],[1,1,1], label = '$\it{ABC123}$')
plt.legend()
plt.show()

as shown by Styling part of label in legend in matplotlib

but this only italicized ABC, not 123, which was also noticed, but left unsolved, by Matplotlib italic font cannot be applied to numbers in the legend?

I have also tried usetex italic symbols in matplotlib? but that changes the fonts which make this figure incompatible with other figures that I'm making.

I'm on Python 3.10.12 and

matplotlib                3.8.1
matplotlib-inline         0.1.3

how can I italicize both letters and numbers, e.g. in ABC123?

Upvotes: 2

Views: 112

Answers (1)

Oskar Hofmann
Oskar Hofmann

Reputation: 807

You can use the font_manager:

import matplotlib.pyplot as plt
import matplotlib.font_manager as font_manager

font = font_manager.FontProperties(style='italic')

plt.plot([1,2,3],[1,1,1], label = 'ABC123')
plt.legend(prop=font)
plt.show()

enter image description here

To use it for x/y ticks or labels, you must use the fontproperties argument:

plt.yticks(fontproperties=font)

Upvotes: 3

Related Questions