I want to plot a coloured contour graph with x,y,z from 3 columns of a comma delimited text file, but each time I try the code below, I get ValueError: too many values to unpack (expected 3) error. I would be grateful if that could be resolved.
I would also like to know if there is another (probably better) code for plotting the 3 independent columns.
This is the code:
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from matplotlib import cm
import numpy as np
import scipy.interpolate
N = 100000
long_col, lat_col, Bouguer_col = np.genfromtxt(r'data.txt', unpack=True)
xi = np.linspace(long_col.min(), long_col.max(), N)
yi = np.linspace(lat_col.min(), lat_col.max(), N)
zi = scipy.interpolate.griddata((long_col, lat_col), Bouguer_col, (xi[None,:], yi[:,None]), method='cubic')
fig = plt.figure()
plt.contourf(xi, yi, zi)
plt.xlabel("Long")
plt.ylabel("Lat")
plt.show()
This is the 'data.txt' sample data.
Lat, Long, Elev, ObsGrav, Anomalies
6.671482000000001022e+00,7.372505999999999560e+00,3.612977999999999952e+02,9.780274000000000233e+05,-1.484474523360840976e+02
6.093078000000000216e+00,7.480882000000001142e+00,1.599972999999999956e+02,9.780334000000000233e+05,-1.492942383352201432e+02
6.092045999999999850e+00,7.278669999999999973e+00,1.462445999999999913e+02,9.780663000000000466e+05,-1.190960417173337191e+02
6.402087429999999912e+00,7.393360939999999992e+00,5.237939999999999827e+02,9.780468000000000466e+05,-8.033459449396468699e+01
6.264082730000000154e+00,7.518244540000000420e+00,2.990849999999999795e+02,9.780529000000000233e+05,-1.114865156192099676e+02
6.092975000000000030e+00,7.482914000000000065e+00,1.416474000000000046e+02,9.780338000000000466e+05,-1.525697779102483764e+02
6.383570999999999884e+00,7.289616999999999791e+00,2.590403000000000020e+02,9.780963000000000466e+05,-8.300666170357726514e+01
6.318417000000000172e+00,7.557638000000000744e+00,1.672036999999999978e+02,9.780693000000000466e+05,-1.246774551668204367e+02
6.253779999999999895e+00,7.268805999999999656e+00,1.059429999999999978e+02,9.781026999999999534e+05,-9.986763240839354694e+01
6.384635000000000282e+00,7.291032000000000401e+00,2.615624000000000251e+02,9.780963000000000466e+05,-8.256190758384764194e+01
If the data file looks exactly like in the question you first of all have 5 columns, which you cannot unpack to 3 variables.
Next, you have a header line which you do not want to be part of the data. Also the header line is separated by ,<space>, while the data is separated by ,.
So in total you need
import numpy as np
a,b,c,d,e = np.genfromtxt("data.txt", unpack=True, delimiter=",", skip_header=1)
Related
I am trying to generate a heatmap from 3D-data in a csv-file. The csv-file has the format x,y,z for each line. The problem is when I create a array to link the values, I can't use float-numbers as keys. When setting the dtype to int in np.loadtext(), the code works fine; but this makes the resolution only half of what the csv-file can replicate. Is there another way of linking the values?
The code so far is:
import numpy as np
import seaborn as sb
import matplotlib.pyplot as plt
fname = 'test18.csv'
x, y, z = np.loadtxt(fname, delimiter=',', dtype=float).T
pltZ = np.zeros((y.max()+1, x.max()+1), dtype=float)
pltZ[y, x] = z
heat_map = sb.heatmap(pltZ, cmap=plt.cm.rainbow)
plt.show()
I have a set of x,y,z data on an irregular grid. I tried to interpolate the same on a regular grid using griddata. Now, how can i extract the output (X,Y,Z) to a file in Python. Any help is much appreciated.
The code is as shown below
import numpy as np
import matplotlib.pyplot as plt
import numpy.ma as ma
from numpy.random import uniform
import matplotlib.pyplot as plt
from scipy.interpolate import griddata
# Read data from an existing dataframe
x = df['X']
y = df['Y']
z = df['WD']
# define grid.
xi = np.linspace(-4900,6000,100)
yi = np.linspace(-5200,7700,100)
# grid the data.
zi = griddata((x, y), z, (xi[None,:], yi[:,None]), method='cubic')
xn=[]
yn=[]
l=1
for i in range(0, len(xi)):
for j in range(0, len(yi)):
xn[l]=xi[i]
yn[l]=yi[j]
l=l+1
d = np.vstack((xn,yn,zi))
np.savetxt("file.csv", d, delimiter=",", fmt='% 4d')
Apparently this method works tills extracting the zi values using griddata, and not beyond that.
I am trying to extract the xi,yi,zi from the griddata and write this information to a file to be used by another program.
Can anyone advice on how to go about it?
I have a sequence of data files which contain two columns of data (x value, and z value). I want to asign each file with a unique constant y value with a loop and then use x,y,z values to make a contour plot.
import glob
import matplotlib.pyplot as plt
import numpy as np
files=glob.glob('C:\Users\DDT\Desktop\DATA TIANYU\materials\AB2O4\synchronchron\OX1\YbFe1Mn1O4_2cyc_600_meth_ox1-*.xye')
s1=1
for file in files:
t1=s1/3
x,z = np.loadtxt(file,skiprows=3,unpack=True, usecols=[0,1])
def f(x, y):
return x*0 +y*0 +z
l1=np.size(x)
y=np.full(l1, t1,dtype=int)
X,Y=np.meshgrid(x,y)
Z = f(X,Y)
plt.contour(X,Y,Z)
s1=s1+1
continue
plt.show()
There is no error in this code, however what I got is an empty figure with nothing.
What mistake did I make?
It is very hard to guess what you're trying to do. Here is an attempt. It supposes that all x-arrays are equal. And that the y really makes sense (although that is hard if the files are read in an unspecified order). To get a useful plot, the data from all the files should be collected before starting to plot.
import glob
import matplotlib.pyplot as plt
import numpy as np
files = glob.glob('........')
zs = []
for file in files:
x, z = np.loadtxt(file, skiprows=3, unpack=True, usecols=[0, 1])
zs.append(z)
# without creating a new x, the x from the last file will be used
# x = np.linspace(0, 15, 10)
y = np.linspace(-100, 1000, len(zs))
zs = np.array(zs)
fig, axs = plt.subplots(ncols=2)
axs[0].scatter(np.tile(x, y.size), np.repeat(y, x.size), c=zs)
axs[1].contour(x, y, zs)
plt.show()
With simulated random data, the scatter plot and the contour plot would look like:
I'm trying to generate some diagrams from an .h5 file but I don't know how to do it.
I'm using pytables, numpy and matplotlib.
The hdf5 files I use contains 2 sets of data, 2 differents curves.
My goal is to get diagrams like this one.
This is what I managed to do for the moment:
import tables as tb
import numpy as np
import matplotlib.pyplot as plt
h5file = tb.openFile(args['FILE'], "a")
for group in h5file.walkGroups("/"):
for array in h5file.walkNodes("/","Array"):
if(isinstance(array.atom.dflt, int)):
tab = np.array(array.read())
x = tab[0]
y = tab[1]
plt.plot(x, y)
plt.show()
x and y values are good but I don't know how to use them, so the result is wrong. I get a triangle instead of what I want ^^
Thank you for your help
EDIT
I solved my problem.
Here is the code :
fig = plt.figure()
tableau = np.array(array.read())
x = tableau[0]
y = tableau[1]
ax1 = fig.add_subplot(211)
ax2 = fig.add_subplot(212)
ax1.plot(x)
ax2.plot(y)
plt.title(array.name)
plt.show()
I want to plot ECG graph using matplotlib . y values from a file having float values and x value is incrementing(ie x ranges from 1 to 1000). went through tutorials and couldn't find any solutions.
Demo Code
import numpy as np
import matplotlib.pyplot as plt
import random
import pickle
#Y Axis : Generate 1000 random numbers
yAxisNumbers = np.random.uniform(1,100,1000)
#Save numbers to a file for demo purpose
with open('numpyData.txt', 'wb') as myFile:
pickle.dump(yAxisNumbers,myFile)
#X Axis :Generate 1000 random numbers
xNumbers = [ x for x in range(1000)]
#Load file data to a list
with open('numpyData.txt', 'rb') as aFile:
yNumbers = pickle.load(aFile)
#Plot and label Graph
plt.plot(xNumbers,yNumbers)
plt.ylabel("Random Float Numbers")
plt.xlabel("Number Count")
plt.title("ECG Graph")
plt.show()
Graph
Here's a minimal answer, based on the scant details provided.
import numpy as np
import matplotlib.pyplot as plt
plt.ion()
Y = np.loadtxt(filename, other needed options)
plt.plot(np.arange(len(Y))+1,Y)
import numpy as np
import pylab as p
aa=np.loadtxt('....your file ....')
x,y= aa.T # transpose data into 2 columns, assuming you have 2 columns
p.plot(x,y)
p.show()