简体   繁体   中英

Reducing decimal places in scientific notation

I have an array read out from a txt file named t_array_hr

['4.155890E+11', '4.155893E+11', '4.155896E+11', ...,'2.723167E+14', '2.723167E+14', '2.723167E+14']

The reason I have left the... is because the full array has thousands of values. I am using this array as the x axis in a graph shown below. My problem is that the x axis values have too many decimal places in scientific notation. I would like to keep them in scientific notation, but reduce and round the decimal places to 2 (4.15589e11 to 4.16e11).

My code is as follows

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from matplotlib import ticker
from matplotlib.ticker import MaxNLocator

stellarModel = open('filepath', 'r')
i = 0
tstep = 0
dtype = object    
dataframe_hr = pd.read_csv(stellarModel,delim_whitespace=True,header=None,low_memory=False,names=np.arange(14),dtype={'0':np.int16,'1':np.int16,'2':np.float16,'3':np.float16,'4':np.float16,'5':np.float16,'6':np.float16,'7':np.float16,'8':np.float16,'9':np.float16,'10':np.float16,'11':np.float16,'12':np.float16,'13':np.float16})
nrows = np.shape(dataframe_hr)[0]
    

T_array_hr = []
L_array_hr = []
t_array_hr = []
r_array_hr = []
M_array_hr=[]    
Mdot_hr=[]
vinf_hr=[]

for i in range(nrows):
        if i%55 == 0:
            T_array_hr.append(dataframe_hr[7][i])
            L_array_hr.append(dataframe_hr[6][i])
            t_array_hr.append(dataframe_hr[1][i])
            r_array_hr.append(dataframe_hr[4][i])
            Mdot_hr.append(dataframe_hr[9][i])
            vinf_hr.append(dataframe_hr[11][i])
            M_array_hr.append(dataframe_hr[8][i])

fig = plt.figure(1, figsize = (10,6))

axes = fig.add_axes([0.2, 0.1, 0.8, 1.0]) # left, bottom, width, height
axes.plot(t_array_hr, Mdot_hr)
axes.set_xlabel('Time')
axes.set_ylabel('Mass Loss')
axes.set_title('Rate of Mass Loss over Time')
axes.invert_yaxis()
axes.xaxis.set_major_locator(MaxNLocator(6))

Does anyone know how to reduce the decimal places without affecting the scientific notation?

在此处输入图像描述

Assuming that your x values are floats (not strings), try adding the following to your code:

import matplotlib.ticker as mtick
axes.xaxis.set_major_formatter(mtick.FormatStrFormatter('%.2e'))

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