简体   繁体   中英

How do I print a Celsius symbol with matplotlib?

I want to print an axis label: "Temperature (℃)". How do I do it? A snippet is this:

# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
x = range(10,60,1)
y = range(-100, 0, 2)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x,y)
ax.set_xlabel('Temperature (℃)')

For that last line I have tried:

ax.set_xlabel('Temperature (℃)'.encode('utf-8'))

ax.set_xlabel(u'Temperature (u\2103)')

ax.set_xlabel(u'Temperature (℃)')

ax.set_xlabel(u'Temperature (\u2103)')

ax.set_xlabel('Temperature (\u2103)')

I just don't get it. I'm using spyder and running the code from there.

Use the LaTeX interpreter to make the degree symbol.

ax.set_xlabel('Temperature ($^\circ$C)')

Here's the results:

在此输入图像描述

ax.set_xlabel(u'Temperature (℃)')

should work:

在此输入图像描述

In [56]: matplotlib.__version__
Out[56]: '1.0.1'

Instead of DEGREE CELSIUS U+2103 (℃), use the DEGREE SIGN U+00B0 (°) followed by the capital letter. This is much safer for several reasons, including font coverage. It is also the way recommended in the Unicode Standard (15.2 Letterlike symbols; p. 481).

To make this work in matplotlib without the LaTex interpreter, use unicode formatting AND the unicode character string

from numpy import arange, cos, pi
from matplotlib.pyplot import (figure, axes, plot, xlabel, ylabel, title,
                               grid, show)
figure(1, figsize=(6,4))
ax = axes([0.1, 0.1, 0.8, 0.7])
t = arange(0.0, 1.0 + 0.01, 0.01)
s = 3*cos(2*pi*t)+25
plot(t, s)

title('Average High Temperature')
xlabel('Year')
ylabel(u'Temp (\u00B0C)')
grid(True)
show()

在此输入图像描述

Or:

ax.set_xlabel(u'Temperature (\N{DEGREE SIGN}C)')

If you want to make it compatible to TeX and non-TeX, then one probably has to use both ways and test with if rcParams['text.usetex'] before-hand. This is how it's done in basemap for example.

Update for Spyder users:

$^\\circ$ - works!

\\N{DEGREE SIGN} - gives me the lower case gamma symbol...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM