4

Today I'm working on a graph, and a section of it has annotations using plt.text. In this annotation I want to write something along the lines of "The price for this month is: USD$3"

Which, without bolding, translates into code like this:

plt.text(0.5,0.9, f"The price for this month is: USD${df.price.iloc[-1]}")

So, what I want to do is to turn the USD${df.price.iloc[-1]} into bold when printing into the graph.

There's a similar question in SO, but for the title, that suggested a notation like this one:

"The price for this month is:' + r"$\bf{" + USD${df.price.iloc[-1]} + "}$"

But it seems that that syntax is invalid, so I'm not sure if it's even possible to have a text that has bold and non-bold parts.

Do you know if it can be done and if so, how it can be done?

Juan C
  • 5,846
  • 2
  • 17
  • 51

1 Answers1

9

This is one way of doing it. You just have to convert the DataFrame value to string


Complete answer

import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame({'price': [2, 4, 8, 3]}, index=['A', 'B', 'C', 'D'])

fig = plt.figure()

plt.text(0.1,0.9, r"The price for this month is: "+ r"$\bf{USD\$" + str(df.price.iloc[-1])  + "}$")
plt.show()

enter image description here

Even concise:

plt.text(0.1,0.9, r"The price for this month is: $\bf{USD\$ %s}$" % str(df.price.iloc[-1]) )

You can also use formatting as

fig = plt.figure()

plt.text(0.1,0.9, r"The price for this month is: " + r"$\bf{USD\$" + '{:.2f}'.format(df.price.iloc[-1]) + "}$")

enter image description here

Sheldore
  • 37,862
  • 7
  • 57
  • 71
  • Thanks @Bazingaa ! It's working perfectly. I have just one more question: does this syntax support formating? I also have to do this for float numbers and percentages, so I wanted to know if I have to manually format through `np.round()` and multiplying by 100 and adding the "%" ? – Juan C Mar 20 '19 at 18:18
  • @JuanC: Check my edited answer – Sheldore Mar 20 '19 at 18:25
  • Thanks again ! Just to be sure I'm understanding correctly, the `r"$ .... $'` notation let's you use html coding to format your graph's text right? – Juan C Mar 20 '19 at 18:27
  • `r"$...$"` enables LaTeX rendering – Sheldore Mar 20 '19 at 18:29
  • 1
    @JuanC: Have a read at [this](https://matplotlib.org/users/usetex.html) – Sheldore Mar 20 '19 at 18:29
  • That's a great resource! Had no idea about that integration. Learning something new every day – Juan C Mar 20 '19 at 18:34
  • Note that you are not using latex here, but what is called mathtext. The respective documentation for mathtext is [here](https://matplotlib.org/tutorials/text/mathtext.html). – ImportanceOfBeingErnest Mar 20 '19 at 21:03
  • @ImportanceOfBeingErnest: Absolutely right :) Thanks for the correct link – Sheldore Mar 20 '19 at 21:09