change decimal point to comma in matplotlib plot

别来无恙 提交于 2019-12-07 13:57:57

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/49445935/change-decimal-point-to-comma-in-matplotlib-plot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!