为什么我不能绘制非标量,一维或(2,n)数组之类的东西?我该如何解决?

问题描述 投票:1回答:1

我是python的新手,我需要它来为大学课程绘制图。我在此代码上出现值错误,我不知道如何解决,我尝试用numpy.asscalar转换V和m,但没有任何改善{“错误必须是标量或一维或(2,n)数组状”)ValueError:err必须为标量或一维或(2,n)数组状}}

我认为问题出在错误栏中,但我确实为此感到困惑。这也是代码

import numpy as np
from matplotlib import pyplot as plt
from scipy.optimize import curve_fit

m=np.array([np.loadtxt('masse.txt')]) 
sigma_m=np.array([np.loadtxt('errore_masse.txt')])
lati=np.array([np.loadtxt('lati.txt')])
sigma_lati=np.array(np.loadtxt('errore_lati.txt'))
h=np.array([np.loadtxt('altezze.txt')]) 
sigma_h=np.array([np.loadtxt('errore_altezza.txt')])

dc=np.array([6.45, 8.56, 10.45, 10.46])
hc=np.array([16.25, 40.80, 75., 17.67])
lpe=np.array([8.56])
a=np.array([7.41])
hpe=np.array([37.3])
lb=np.array([10.46])

rc=dc/2
Vc=2*np.pi*a**2 *hc
sigma_rc=sigma_lati/2
sigma_Vc=Vc*2*(0.01/dc)

Vpe=6*lpe*a*hpe
sigma_Vpe=((lpe*a)**2 *(0.01)**2 +(lpe*hpe)**2 *(0.01)**2 +(hpe*a)**2 *(0.01)**2)

Vp=lb**2
sigma_Vp=2*Vp*(0.01/lb)

V=np.array([np.loadtxt('volumi.txt')])
sigma_V=np.array([np.loadtxt('errore_volumi.txt')])

def line (x, a, q):
    """funzione retta
    """
    return a*x+q

plt.figure('Grafico massa-volume oggetti di ottone')
plt.errorbar(m, sigma_m, V, sigma_V, marker='.', fmt='.')

popt, pcov=curve_fit(m, V, line)

a_fit, q_fit= popt

sigma_a_fit, sigma_q_fit=np.sqrt(pcov.diagonal())

print(a_fit, q_fit, sigma_a_fit, sigma_q_fit)
x=np.linspace(10.675, 34.080, 10)
plt.plot(x, line(x, a_fit, q_fit))
plt.xlabel('Volume [mm$^3$]')
plt.ylabel('Massa [g]')
plt.grid (ls='dashed', which='both')

plt.show()

感谢您的帮助

python arrays numpy valueerror
1个回答
0
投票

您收到的值错误是因为您在错误栏中混合了值。使用时,请检查the documentation

您的问题来自此行:

plt.errorbar(m, sigma_m, V, sigma_V, marker='.', fmt='.')

首先,您应使用m.shapesigma_m.shape等检查所有这些变量的形状。它们都必须具有相同的形状,否则后两个值应该是您已切换的错误。假设m是您的x数据,V是您的y数据,则应该具有以下内容:

plt.errorbar(m, V, xerr=sigma_m, yerr=sigma_V, marker='.', fmt='.')
© www.soinside.com 2019 - 2024. All rights reserved.