简体   繁体   English

减少科学计数法中的小数位数

[英]Reducing decimal places in scientific notation

I have an array read out from a txt file named t_array_hr我从名为 t_array_hr 的 txt 文件中读出了一个数组

['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.我在下图中使用这个数组作为 x 轴。 My problem is that the x axis values have too many decimal places in scientific notation.我的问题是 x 轴值在科学计数法中的小数位太多。 I would like to keep them in scientific notation, but reduce and round the decimal places to 2 (4.15589e11 to 4.16e11).我想让它们保持科学计数法,但将小数位减少并四舍五入到 2(4.15589e11 到 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:假设您的 x 值是浮点数(不是字符串),请尝试将以下内容添加到您的代码中:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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