-1

I am reading data from a text file but when I do so, I need to multiple this values like 3*sqrt(col1)= x1.append(3*math.sqrt(float(p[1]))) in plot function. How can I multiple column number data before plotting? For example, I will multiple col3 data by 3*sqrt(col3) and after plot that data.

#-------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()
Nobody
  • 79
  • 13

1 Answers1

2

Again, this is easier if you just use numpy arrays from the start.

By reading the data in as I showed you in your last question, your data will already be in numpy arrays. Then you can use the numpy.sqrt function to perform the square-root operation element-wise on the array.

#-------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()

enter image description here

However, if you really want to stick with your old code, it can be fixed by

  1. fixing the indentation,

  2. changing the indexing to p[0], p[1] and p[2] (instead of p[1], p[2] and p[3])

This code produces the same plot as above:

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()
tmdavison
  • 64,360
  • 12
  • 187
  • 165
  • thanks Tom i will change the code regarding your solution. Also I have one question, For example, I want to define xlabel with column 1. plt.xlim(0,col1). Because I wan to see in the x range, col1 number – Nobody Jun 15 '18 at 10:36