I'm using python 2.7.13 with matplotlib 2.0.0 on Debian. I want to change the decimal marker to a comma in my matplotlib plot on both axes and annotations. However the solution posted here does not work for me. The locale option changes successfully the decimal point but does not imply it in the plot. How can I fix it? I would like to use the locale option in combination with the rcParams setup. Thank you for your help.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
#Locale settings
import locale
# Set to German locale to get comma decimal separater
locale.setlocale(locale.LC_NUMERIC, 'de_DE.UTF-8')
print locale.localeconv()
import numpy as np
import matplotlib.pyplot as plt
#plt.rcdefaults()
# Tell matplotlib to use the locale we set above
plt.rcParams['axes.formatter.use_locale'] = True
# make the figure and axes
fig,ax = plt.subplots(1)
# Some example data
x=np.arange(0,10,0.1)
y=np.sin(x)
# plot the data
ax.plot(x,y,'b-')
ax.plot([0,10],[0.8,0.8],'k-')
ax.text(2.3,0.85,0.8)
plt.savefig('test.png')
Here is the produced output: plot with point as decimal separator
I think that the answer lies in using Python's formatted print, see Format Specification Mini-Language. I quote:
Type: 'n'
Meaning: Number. This is the same as 'g'
, except that it uses the current locale setting to insert the appropriate number separator characters.
For example
import locale
locale.setlocale(locale.LC_ALL, 'de_DE')
'{0:n}'.format(1.1)
Gives '1,1'
.
This can be applied to your example using matplotlib.ticker. It allows you to specify the print format for the ticks along the axis. Your example then becomes:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import locale
# apply German locale settings
locale.setlocale(locale.LC_ALL, 'de_DE')
# make the figure and axes
fig, ax = plt.subplots()
# some example data
x = np.arange(0,10,0.1)
y = np.sin(x)
# plot the data
ax.plot(x, y, 'b-')
ax.plot([0,10],[0.8,0.8],'k-')
# plot annotation
ax.text(2.3,0.85,'{:#.2n}'.format(0.8))
# reformat y-axis entries
ax.yaxis.set_major_formatter(ticker.StrMethodFormatter('{x:#.2n}'))
# save
plt.savefig('test.png')
plt.show()
Which results in
Note that there is one thing that is a bit disappointing. Apparently the precision cannot be set with the n
format. See this answer.