Python Plot- 乘以图中的数据

Python Plot- Multiple the data in plot figure

我正在从文本文件中读取数据,但是当我这样做时,我需要在 plot 函数中将此值乘以 3*sqrt(col1)= x1.append(3*math.sqrt(float(p[1])))。如何在绘图前使用多个列号数据?例如,我将 col3 数据乘以 3*sqrt(col3) 并绘制该数据。

#-------input.dat---------
#   x        y     z
# col 1    col 2  col 3
# 3          5      5
# 5          6      4
# 7          7      3
import matplotlib.pyplot as plt
import numpy as np
import pylab as pl
import math

data = open('input.dat')
lines = data.readlines()
data.close()
x1=[]
y1=[]
z1=[]
plt.plot(1)
for line in lines[2:]:
p= line.split()
x1.append(3*math.sqrt(float(p[1])))
y1.append(3*math.sqrt(float(p[2])))
z1.append(3*math.sqrt(float(p[3])))
x=np.array(x1)
y=np.array(y1)
z=np.array(z1)
plt.subplot(311)
plt.plot(x,'b',label=" X figure ")
plt.subplot(312)
plt.plot(y,'r',label=" Y figure ")
plt.subplot(313)
plt.plot(x,z,'g',label=" X,Z figure ")
plt.show()

同样,如果您从一开始就使用 numpy 数组,这会更容易。

通过读取我向您展示的 , your data will already be in numpy arrays. Then you can use the numpy.sqrt 函数中的数据,对数组按元素执行平方根运算。

#-------input.dat---------
#   x        y     z
# col 1    col 2  col 3
# 3          5      5
# 5          6      4
# 7          7      3
import matplotlib.pyplot as plt
import numpy as np

data = np.genfromtxt('input.dat', skip_header=2)

x = 3. * np.sqrt(data[:, 0])
y = 3. * np.sqrt(data[:, 1])
z = 3. * np.sqrt(data[:, 2])

plt.subplot(311)
plt.plot(x, 'b', label=" X figure ")
plt.subplot(312)
plt.plot(y, 'r', label=" Y figure ")
plt.subplot(313)
plt.plot(x, z, 'g', label=" X,Z figure ")
plt.show()

但是,如果您真的想坚持使用旧代码,可以通过

修复它
  1. 修复缩进,

  2. 将索引更改为 p[0]p[1]p[2](而不是 p[1]p[2]p[3])

此代码生成与上面相同的图:

import matplotlib.pyplot as plt
import numpy as np
import pylab as pl
import math

data = open('input.dat')
lines = data.readlines()
data.close()
x1=[]
y1=[]
z1=[]
plt.plot(1)
for line in lines[2:]:
    p= line.split()
    x1.append(3*math.sqrt(float(p[0])))
    y1.append(3*math.sqrt(float(p[1])))
    z1.append(3*math.sqrt(float(p[2])))
x=np.array(x1)
y=np.array(y1)
z=np.array(z1)
plt.subplot(311)
plt.plot(x,'b',label=" X figure ")
plt.subplot(312)
plt.plot(y,'r',label=" Y figure ")
plt.subplot(313)
plt.plot(x,z,'g',label=" X,Z figure ")
plt.show()