Matplotlib plots no line plots; crosses, circles and triangles work - python

I'm trying to plot some measurement data with Matplotlib.
With the code shown below i get the plot window and gui but no plot is drawn. If i change the plot kind to circles or crosses it works just fine.
# coding=utf-8
import matplotlib.pyplot as plt
import csv
with open("AgPVP8.2.171g1L#2.csv") as csvfile:
reader = csv.reader(csvfile, delimiter=",")
frequencies = []
phases = []
for row in reader:
frequency = float(row[0])
phase = float(row[4])
frequencies.append(frequency)
phases.append(phase)
plt.plot([frequencies], [phases], "b-")
plt.xscale("log")
plt.show()

The problem is that frequencies and phases only exist in the scope of with open(..., you must place it within this:
import matplotlib.pyplot as plt
import csv
with open("AgPVP8.2.171g1L#2.csv") as csvfile:
reader = csv.reader(csvfile, delimiter=",")
frequencies = []
phases = []
for row in reader:
frequency = float(row[0])
phase = float(row[4])
frequencies.append(frequency)
phases.append(phase)
plt.plot(frequencies, phases, "-b")
plt.xscale("log")
plt.show()

plt.plot(x,y) requires x and y to be lists (or in general sequences) or arrays.
Here, you are trying to plot a list of a list, i.e. [x] is not the same as x.
So in your code you need to replace plt.plot([frequencies], [phases], "b-") with
plt.plot(frequencies, phases, "-b")
The complete code should then look like:
import matplotlib.pyplot as plt
import csv
with open("AgPVP8.2.171g1L#2.csv") as csvfile:
reader = csv.reader(csvfile, delimiter=",")
frequencies = []
phases = []
for row in reader:
frequency = float(row[0])
phase = float(row[4])
frequencies.append(frequency)
phases.append(phase)
plt.plot(frequencies, phases, "b-")
plt.xscale("log")
plt.show()
I would suggest to have a look at numpy.loadtxt or numpy.genfromtxt. Both would make is much easier to read in a csv file, e.g. in this case
import matplotlib.pyplot as plt
import numpy as np
frequencies, phases = np.loadtxt("AgPVP8.2.171g1L#2.csv", unpack=True, usecols = (0,4), delimiter=",")
plt.plot(frequencies, phases, "b-")
plt.xscale("log")
plt.show()

Related

Pose robot visualization as direction from csv

Sorry for all mistakes, English is not my native language. I have a CSV file with pose data in X,Y,Z coordinates. I managed to visualize it as dots using matplotlib.pyplot and pandas, but what I want is direction, so that dots was linked and first and last dots was of a different color. This is code I use for pose visualization:
import pandas as pd
import csv
import matplotlib.pyplot as plt
import numpy as np
str_filename = 'sensor_data.csv'
fh = open(str_filename, encoding="utf-8")
csv_reader = csv.reader(fh, delimiter = ";")
csv_header = next(csv_reader)
fh.close()
df_sig = pd.read_csv(str_filename, delimiter=";", header=None, skiprows=1, names=csv_header)
x = np.array(df_sig["Pose X"])
y = np.array(df_sig["Pose Y"])
plt.plot(x, y, 'd', color = 'black')
plt.title('Pose')
plt.savefig('Pose Visualization.pdf')
Appreciate any help.

How to calculate small peak in python with CSV

I have a 2 column txt file which I want to know the value of the small bump around 0.8V for (see picture). What is the best way to calculate this. Image
import numpy as np
import matplotlib.pyplot as plt
data = np.genfromtxt("220525_01-O2-LSV-LMOink-1600rpm-rep1.txt", delimiter=";", names=["x", "y"])
data_2 = np.genfromtxt("220525_01-O2-LSV-LMOink-1600rpm-rep2.txt", delimiter=";", names=["x", "y"])
plt.plot(data['x'], data['y'], label='ORR polarization repetition 1')
plt.plot(data_2['x'], data_2['y'], label='ORR polarization repetition 2')
plt.title('LSV LMO-ink')
plt.xlabel('Potential Applied ($V$)')
plt.ylabel('Current ($A$)')
plt.grid()
plt.legend()
plt.savefig('ORR.png', dpi=100)
plt.show()
I tried it with find_peak. But did not succeed.

Python Line Chart with matplotlib.pyplot not displayed correctly - I get a straight diagonal line

I have the following code:
import matplotlib.pyplot as plt
import csv
with open('results simulation.csv', newline='') as f:
reader = csv.reader(f)
data = list(reader)
Generation = data[0]
Points = data[1]
plt.plot(Generation, Points)
plt.title('Points for every Generation')
plt.xlabel('Generation')
plt.ylabel('Points')
plt.show()
And this is the chart that I get:
As you can I get a straight line, even though the values are different 😅
Any ideas?

How to plot data from different files?

I'm trying to plot data from different text files.
I've had to manipulate data so I could construct the graphic that I desire for just one document. All other documents are in the same way. But I can't see how I can plot all in one panel. The code that I tried for the loop of all files was:
import numpy as np
import matplotlib.pyplot as plt
filenames=["b_10.txt","b_100.txt","b_500.txt","b_1000.txt"]
for i in filenames:
with open(i) as f:
data = f.read()
data = data.split('\n')
x = [row.split(' ')[0] for row in data]
y = [row.split(' ')[-1] for row in data]
x
a=list(map(str.strip, y))
trip_list = [item.strip('\tall\t') for item in y]
yy = np.array(trip_list[1:12])
yy
xx= np.array(x[21:32])
xx
fig = plt.figure()
plt.hold(True)
plt.ylabel('Precisão Interpolada')
plt.xlabel('Recall')
plt.plot(xx,yy,'-',label="Precisão Interpolada vs Recall")
plt.show()
It gave me an error:
ValueError: could not convert string to float:
and a blank panel
enter image description here

python plotting overrides data

I have lot of binary and ascii files in one folder. I am reading them using glob module. Doing processing of the binary data so that I can plot them. And finally, I am trying to plot simplified binary data in one subplot and normal ascii file in another subplot. The problem I am facing is that it can generate plots for the corresponding binary files. But for the ascii files it just simply override the previous files and always generates the same plot. Here is the simplied version of the code for an example-
import glob
import numpy as np
from struct import unpack
import matplotlib.pyplot as plt
chi = sorted(glob.glob('C:/Users/Desktop/bin/*.chi'))
for index,fh in enumerate(chi):
data = np.genfromtxt(fh, dtype = float)
x = [row[0] for row in data]
y = [row[1] for row in data]
binary = sorted(glob.glob('C:/Users/Desktop/bin/*.bin'))
for count,FILE in enumerate(binary):
F = open(FILE,'rb')
B = unpack('f'*1023183, F.read(4*1023183))
A = np.array(B).reshape(1043, 981)
F.close()
#a = something column 1 # some further processing
#b = something column 2 # and generates 1D data
fig = plt.figure(figsize=(11, 8.0))
ax1 =fig.add_subplot(211,axisbg='w')
ax1.plot(a,b)
ax2 =fig.add_subplot(212, axisbg ='w')
ax2.plot(x,y)
plt.show()
Can somebody please explain why the files are replacing each other during plotting only for one set of data where the other set is plotting correctly?
the structures of the loops is not correct in your example, you must have the plot command inside the loop over the ascii file, else only the last one is plotted. This should work:
try it like this:
import glob
import numpy as np
from struct import unpack
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(11, 8.0))
chi = sorted(glob.glob('C:/Users/Desktop/bin/*.chi'))
for index,fh in enumerate(chi):
data = np.genfromtxt(fh, dtype = float)
x = [row[0] for row in data]
y = [row[1] for row in data]
ax1 =fig.add_subplot(211, axisbg ='w')
ax1.plot(x,y)
binary = sorted(glob.glob('C:/Users/Desktop/bin/*.bin'))
for count,FILE in enumerate(binary):
F = open(FILE,'rb')
B = unpack('f'*1023183, F.read(4*1023183))
A = np.array(B).reshape(1043, 981)
F.close()
#a = something column 1 # some further processing
#b = something column 2 # and generates 1D data
ax2 =fig.add_subplot(212,axisbg='w')
ax2.plot(a,b)
plt.show()

Categories