Plotting a graph using matplotlib with two lists - python

I am trying to plot a graph after having imported data from a CSV file and stored it as two separate lists. Is it possible for matplotlib to plot a graph using a list of strings, or is it necessary for the lists two be lists of "int" ?
If not, why is the following code not working?
Error prompted:
invalid literal for int() with base 10: '02_13_2014'
My code:
import csv
import numpy as np
from numpy import genfromtxt
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
with open('pytdef.csv','r') as f:
reader = csv.reader(f)
for row in reader:
print (row)
first_column= ['Date']
second_column = ['Value']
Date_list = []
Value_list = []
with open('pytdef.csv') as f:
reader = csv.reader(f)
for row in reader:
Date_list.append(row[0])
with open('pytdef.csv') as f:
reader = csv.reader(f)
for row in reader:
Value_list.append(row[1])
print (Date_list)
print (Value_list)
Date_list = list(map(int,Date_list))
print (Date_list)
print (Value_list)
fig = plt.figure()
plt.plot_date(x=Date_list, y=Value_list)
plt.show()

I think the problem here is your date. The code here is a lot simpler if you just use pandas
#!/usr/bin/env python
%matplotlib inline
import pandas as pd
import matplotlib.pyplot as plt
from datetime import date
columns = ['dates', 'value']
data = pd.read_csv('/location_of_file/file_name.csv', header=False, names=columns)
I'm assuming your data looks something like this...
then format the date
data['dates'] = [date(int(x.split('_')[2]), int(x.split('_')[0]),
int(x.split('_')[1])) for x in data.dates]
plt.plot(data.dates, data.value);

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.

sequence of ordered numbers in python3

I would like to generate sequence of ordered numbers which is of same length of some other list. I have tried
def parse_data_from_file(filename):
times = []
temperatures = []
with open(filename) as csvfile:
reader = csv.reader(csvfile, delimiter=',')
next(reader)
for row in reader:
times.append(row[0])
temperatures.append(float(row[1]))
return times, temperatures
The issue is time is not getting represnted properly on x-axis as attached here:
You haven't said how you're making the plots. I'll assume you're using matplotlib, which is probably the most popular plotting package for Python.
I know that when I'm working with dates or times, I usually use datetime.strptime() to get the data into a datetime format that Python likes:
from datetime import datetime
# assume your date info looks like 08-Jun-2022 14:22:22
dt = datetime.strptime(row[0], '%d-%b-%Y %H:%M:%S')
times.append(dt)
Matplotlib has a convenience function date2num that converts a datetime object to a format that it likes to use. Their official example is here. Here is an even shorter example for you:
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import matplotlib
fig, ax = plt.subplots()
t = matplotlib.dates.date2num(times)
y = temperatures
ax.plot(t, y)
ax.xaxis.set_major_locator(mdates.MonthLocator(bymonth=(1, 7)))

Matplotlib: blank plot and window won't close

I'm trying to plot a curve using the data from a csv file using:
import matplotlib.pyplot as plt
from csv import reader
with open('transmission_curve_HST_ACS_HRC.F606W.csv', 'rw') as f:
data = list(reader(f))
wavelength_list = [i[0] for i in data[1::]]
percentage = [i[1] for i in data[1::]]
plt.plot(wavelength_list, percentage)
plt.show()
But all it make is opening a completely blank window and I can't close it unless I close the terminal.
The csv file looks like this:
4565,"0,00003434405472044760"
4566,"0,00004045191689260860"
4567,"0,00004656394357747830"
4568,"0,00005267963655205460"
4569,"0,00005879949856084820"
Do you have any idea why?
You need to modify three things in your code:
Change 'rw' to 'r' when you read from the file
Correct the way you iterate over data
Convert the numbers from the second column to float
import matplotlib.pyplot as plt
from csv import reader
with open('transmission_curve_HST_ACS_HRC.F606W.csv', 'r') as f:
data = list(reader(f))
wavelength_list = [i[0] for i in data]
percentage = [float(str(i[1]).replace(',','.')) for i in data]
plt.plot(wavelength_list, percentage)
plt.show()
Content of the csv file:
4564,"0,00002824029270045730"
4565,"0,00003434405472044760"
4566,"0,00004045191689260860"
4567,"0,00004656394357747830"
4568,"0,00005267963655205460"
4569,"0,00005879949856084820"

Generating heatmap from frames

I have an issue as follow, i have coordinates x, y, z and r. Each of point is a Frame. Based on Frames want to generate heat-map with python. What i did till now, i imported the following frames:
-1.52588e-05 -1.52588e-05 8.17212e-06 300
-220.414 -220.305 217.847 79.5859
-220.899 220.54 -219.881 79.1004
219.275 218.495 -221.124 78.8756
-216.911 220.674 218.582 78.848
218.126 -219.362 221.977 78.0233
-222.961 -224.281 -204.107 75.7191
225.267 222.614 221.81 74.7329
parse it as well. From here i know is actually nothing really.
as far as i'm concerned, generating heat-map based on frames.
I don't know how should i do after importing frames.I'm really lost in context.
Could someone give tips or way of doing i.e steps...
thanks
the code below is not work as well
import csv
import seaborn as sns
result = [[]]
with open("data.csv") as csvfile:
reader = csv.reader(csvfile, quoting=csv.QUOTE_NONNUMERIC)
for row in reader:
result.append(row)
print(result)
Try following code:
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
with open('data.txt', 'r') as f:
data = f.read().replace(' ', ' ')
with open('data.txt', 'w') as f:
f.write(data)
df = pd.read_csv('data.txt', sep=' ', header=None)
sns.heatmap(df, annot=True)
plt.show()
Output:

Generating simple plot from csv using Pandas in Python

I'm trying to make a graph of the first column ('Time') of a csv file plotted against the the second column ('Bid').
Here's what I have so far.
import pandas as pd
import datetime
import csv
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
headers = ['Time','Bid','Ask']
df = pd.read_csv('quotes_format.csv')
x = df['Time']
y = df['Bid']
plt.plot(x,y)
plt.gcf().autofmt_xdate()
plt.show()
The csv file looks something like this
This fails and returns exit code 1. How would I fix this so it would generate the graph I'm looking for?
You can specify what the names of each column in the dataframe are with the parameter names.
headers = ['Time','Bid','Ask']
df = pd.read_csv('quotes_format.csv', names=headers)
Here is the documentation for the pandas read_csv function.

Categories