Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to create ticks with temperature symbol - °C - in matplotlib

I have a chart with a y axis which represents the temperatures on certain days of a year. I'd like to get the degrees Celsius into the actual ticks on the y label. Here's the code I've used so far and the chart below it.

plt.ylabel('°C',fontsize = 30)
plt.yticks(np.arange(miny,maxy, step=20))
plt.tick_params(labelsize=20)

enter image description here

Previous answers focused on unicode issues, but I found matplotlib is fine with the °C notation as part of a string. My issue is how to get it into the ticks on the y axis.

Is there anyway to do this with tick_params?

Thanks for any advice.

like image 865
ZakS Avatar asked Jan 29 '23 04:01

ZakS


1 Answers

Two options:

  • (Mis)use a matplotlib.ticker.EngFormatter
  • use a matplotlib.ticker.StrMethodFormatter

In both cases, supply the unit "°C".

import matplotlib.pyplot as plt
from matplotlib.ticker import EngFormatter, StrMethodFormatter

fig, (ax,ax2) = plt.subplots(ncols=2)

ax.plot([0,1],[-35,30])
ax.yaxis.set_major_formatter(EngFormatter(unit=u"°C"))

ax2.plot([0,1],[-35,30])
ax2.yaxis.set_major_formatter(StrMethodFormatter(u"{x:.0f} °C"))

plt.tight_layout()
plt.show()

enter image description here

like image 196
ImportanceOfBeingErnest Avatar answered Jan 31 '23 12:01

ImportanceOfBeingErnest