【问题标题】:Python Plot- Multiple the data in plot figurePython Plot - 多个图中的数据
【发布时间】:2018-06-15 09:34:17
【问题描述】:

我正在从文本文件中读取数据,但是当我这样做时,我需要在绘图函数中将这些值倍增,例如 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()

【问题讨论】:

  • 问题是什么?你得到哪个错误?
  • @Joaquin 数学域错误!
  • 这可能意味着您的表格中有负数。当您尝试对负数执行 sqrt 时,您会收到此错误。

标签: python python-3.x matplotlib math math.sqrt


【解决方案1】:

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

通过读取我向您展示的in your last question 中的数据,您的数据将已经在numpy 数组中。然后您可以使用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()

【讨论】:

  • 感谢 Tom,我将更改有关您的解决方案的代码。我还有一个问题,例如,我想用第 1 列定义 xlabel。plt.xlim(0,col1)。因为我想在 x 范围内看到 col1 数字
猜你喜欢
  • 2018-01-13
  • 1970-01-01
  • 2016-08-01
  • 2021-07-23
  • 2016-01-10
  • 2018-12-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多