Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
435 views
in Technique[技术] by (71.8m points)

Python matplotlib: How can I replace all decimal points in plotted numbers with commas?

I need in figures (in python matplotlib) to replace all decimal points with commas in the plots, legends, and titles for floats numbers and keep precision.

I tried

import locale
# Set to German locale to get comma decimal separater
locale.setlocale(locale.LC_NUMERIC, 'pl_PL')
rcParams['axes.formatter.use_locale'] = True 

then

'$x=${:#.4n}'.format(x)

where x is the float numbers. There are lef legends without solution and a lot of manual twisting.

Regards

Sample figure

enter image description here

I had to put my sample code in Google Drive because here it wouldn't let me.

from   pylab                import *
from   matplotlib.ticker    import StrMethodFormatter


def quit_figure(event):
    if event.key == 'escape':
       plt.close(event.canvas.figure)
    if event.key == 'f10':
       plt.savefig('0.png',dpi=150)

def graph_setup():
    rcParams['toolbar'] = 'None'       
    rcParams['axes.grid'] = True    
    rcParams['axes.linewidth']   = 2 # set the value    globally
    rcParams['font.size']        = 16# set the value globally
    rcParams["font.family"] = "Times New Roman"
    rcParams['mathtext.fontset'] = 'stix'
    rcParams['legend.fontsize']  = 24
    rc('lines', linewidth=2, linestyle='-',marker='o')
    fig  = figure(num=None,  frameon='False', figsize=(12, 6), facecolor='w')
    quit = gcf().canvas.mpl_connect('key_press_event', quit_figure)
    okno = get_current_fig_manager()
    okno.window.wm_geometry('+65+150')
    okno.window.resizable(False, False)


# ***********************************************
# I DIDN'T WONT IT BEFORE WHAT IS BELOW
# BUT IF SOLVES ALL PROBLEMS IT WILL FINE FOR ME
# ***********************************************

    import locale
    # Set to German locale to get comma decimal separater
    locale.setlocale(locale.LC_ALL, 'pl_PL')
    rcParams['axes.formatter.use_locale'] = True

# *****************************************************************
# BEFORE I SET UP 2 DIGITS AFTER DECIMAL POINT 
# *****************************************************************
    # fig  = gca().xaxis.set_major_formatter(StrMethodFormatter('{x:,.2f}')) # 2 decimal places
    # fig  = gca().yaxis.set_major_formatter(StrMethodFormatter('{x:,.2f}')) # 2 decimal places
    
# *****************************************************************
# I TRIED THIS BELOW WITH 'n' - IT DOESN'T WORKS
# ALWAY TEH ONE POSITION IS LACK
# *****************************************************************

    fig  = gca().xaxis.set_major_formatter(StrMethodFormatter('{x:#.2n}')) # 2 decimal places
    fig  = gca().yaxis.set_major_formatter(StrMethodFormatter('{x:#.2n}')) # 2 decimal places


graph_setup()

dt=0.10
t = arange(0,1+dt,dt) 
v = 17.0
s = v*t
m=5.3


# ****************************************************************
# IN LABELS
# BEFORE I COULDN'T WORRY ABOUT PRECISION IN LABELS BUT NO COMASS
# ****************************************************************

plot(t,s,label='$s=%1.2fcdot t$'%v)

# ***********************************************************************************
# BEFORE I COULDN WORRY ABOUT PRECISION 
# NOW DIGITS AFTER COMMA IS MISSING 
# {:#.2n} DOESN'T MEAN 2 DIGITS AFTER COMMA - IT MUST BE ALWAYS CHANED DEPENDING ON HOW LONG DIGITS ARE
# NO ONE UNIVERSAL SOLUTION
# ***********************************************************************************

plot(t,s+1,label='$s=${:#.2n}'.format(v))

# ****************************************************************
# IN TITLES
# BEFORE I COULDN'T WORRY ABOUT PRECISION IN LABELS BUT NO COMASS
# ****************************************************************

title('$m=%1.2f,mathrm{kg}$'%m,fontsize = 16)

# ****************************************************************************************
# NOW IS TO MANY HANYD FIXATION
# {:#.2n} DOESN'T MEAN 2 DIGITS AFTER COMMA - IT MUST BE ALWAYS CHANED DEPENDING ON HOW LONG DIGITS ARE
# NO ONE UNIVERSAL SOLUTION
# ****************************************************************************************

title('$m=${:#.2n}'.format(m)+'$mathrm{kg}$',fontsize = 16)


xlabel('Time $t$, s')
ylabel('Distance $s$, m')
xticks(linspace(t.min(), t.max(), 10))  # arbitrary chosen
yticks(linspace(s.min(), s.max(), 5))   # arbitrary chosen
axes = gca()
x_min, x_max = axes.get_xlim()
y_min, y_max = axes.get_ylim()
legend(loc='best')

show()

And the second one iseven harder! I put in loops digits into label and here i have no idea how to replace dots with commas.

Digits in loops - HOW TO COMMAS ??

legend_1=legend(przechowalnia_dam,loc=1, bbox_to_anchor=(1.0, 1.0),title='$c$ - t?umnienie',fontsize = 16)

Example 2 - even hardes !!! Digits in LOOPS - line 235 236 of the code

question from:https://stackoverflow.com/questions/65836830/python-matplotlib-how-can-i-replace-all-decimal-points-in-plotted-numbers-with

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It looks like you'll need to explicitly call local.format_string(…)

Here's the comparison based on the labels in your example:

>>> '$s=%1.2fcdot t$'%v
'$s=17.00\cdot t$'
>>> locale.format_string('$s=%1.2fcdot t$', v)
'$s=17,00\cdot t$'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...