Python.Module.Matplotlib #python #Python #PythonModules #Matplotlib #matplotlib #Modules #Plotting
PYTHON MATPLOTLIB MODULE
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
import numpy as np
# parameter handling
#
#
def plotter_math(file_out):
# To add
# - change the scale of y and x axis to ie logarithmic
import numpy as np
#%matplotlib inline
import matplotlib.pyplot as plt
# #
# Data
# Here we establish the linear space of the x axis
# np.linspace(start, finish, increment)
x = np.linspace(0, 10, 100)
# Here we establish the correspondent y function
# List of available mathematical functions:
# https://docs.scipy.org/doc/numpy-1.13.0/reference/routines.math.html
y = np.sin(x)
z = np.sqrt(x)
j = np.cos(x)
# #
# Plot
# Initialize the figure
# Possible parameters:
# figsize(4,3) -> in inches ( or default )
# dpi(integer) -> dots per inch (or default)
fig = plt.figure()
# Initialize the axes
ax = plt.axes()
# Plot
# You can add more plot-lines but always provide two lists.
# 1. We can add the same (plot) or other kinds of plots as seen below:
# ax.scatter(x, j)
# ax.hist(y, bins = 10)
#
# 2. We can alter the color / presentation of the line by using [fmt]
# ax.plot((x, y, [fmt], ...)
# ie r+
# * See 'FMT NOTES' at the bottom for a full list.
#
# 3. We can alter the linewidth and markersize (either or, or combined)
# ax.plot(x, z, 'r+', label="sqrt", markersize=10)
# ax.plot(x, y, 'r-', linewidth=3)
ax.plot(x, y, label="Moment")
ax.plot(x, z, label="sqrt")
#ax.plot(x, z, 'r+', label="sqrt", markersize=10)
#ax.plot(x, y, 'r-', linewidth=3)
# Enable grid
ax.grid(True)
# Set x label
ax.set_xlabel('Time, s * 0.01')
# Set y label
ax.set_ylabel('Velocity, m/s')
# Set legend
ax.legend(loc='upper right', bbox_to_anchor=(1, -0.2))
# save and close plotter.
plt.savefig(file_out, dpi=600, bbox_inches='tight')
plt.close()
def plotter_simple(list_x, list_y, file_out):
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(4,3))
ax = fig.add_subplot(111)
ax.plot(list_x, list_y, 'r.',label='Moment')
ax.set_xlabel('Time, s * 0.01')
ax.set_ylabel('Moment of Gyro, m/s')
ax.legend(loc='upper right', bbox_to_anchor=(1, -0.2))
ax.grid(True)
plt.savefig(file_out, dpi=600, bbox_inches='tight')
plt.close()
lista1 = [ 1, 2, 3, 4, 5 ]
lista2 = [ 1, 4, 9, 16, 25 ]
plotter_simple(lista1, lista2, 'PlotterTest3.pdf')
plotter_math('PlotterMathTest19.pdf')
# fig = plt.figure()
# ax = plt.axes()
# x = np.linspace(0, 10, 1000)
# ax.plot(x, np.sin(x));
# #########################################################################
# #########################################################################
# DOCUMENTATION
#
# 1. FMT_NOTES
# Format Strings
# A format string consists of a part for color, marker and line:
# fmt = '[color][marker][line]'
#
# Each of them is optional. If not provided, the value from the style cycle is
# used. Exception: If line is given, but no marker, the data will be a line
# without markers.
#
# Colors
#
# The following color abbreviations are supported:
#
# Character color
#
# 'b' blue
# 'g' green
# 'r' red
# 'c' cyan
# 'm' magenta
# 'y' yellow
# 'k' black
# 'w' white
# If the color is the only part of the format string, you can additionally use
# any matplotlib.colors spec, e.g. full names ('green') or hex strings ('#008000').
#
# Markers
#
# character description
#
# '.' point marker
# ',' pixel marker
# 'o' circle marker
# 'v' triangle_down marker
# '^' triangle_up marker
# '<' triangle_left marker
# '>' triangle_right marker
# '1' tri_down marker
# '2' tri_up marker
# '3' tri_left marker
# '4' tri_right marker
# 's' square marker
# 'p' pentagon marker
# '*' star marker
# 'h' hexagon1 marker
# 'H' hexagon2 marker
# '+' plus marker
# 'x' x marker
# 'D' diamond marker
# 'd' thin_diamond marker
# '|' vline marker
# '_' hline marker
#
#
# Line Styles
#
# character description
# '-' solid line style
# '--' dashed line style
# '-.' dash-dot line style
# ':' dotted line style
#
#
# Example format strings:
#
# 'b' # blue markers with default shape
# 'ro' # red circles
# 'g-' # green solid line
# '--' # dashed line with default color
# 'k^:' # black triangle_up markers connected by a dotted line
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 30 16:56:00 2017
@author: P.Doulgeridis
"""
import os
import sys
import time
import csv
import numpy as np
import matplotlib.pyplot as plt
from datetime import datetime
#file_in = sys.argv[1]
def csvtolist(input_csv):
'''
Name: csvtolistadv
Function: Converts an csv file into a list of lists
Each line of an csv file will be stored in a list, all such lists
will be stored in a central list [[line1][line2][line3]]
Input: /path/to/filename or sys.argv[1]
Output: List of Lists -> [[Field1;Field2][Field2;Field2]]
Usage: csvtolistoflists(r'\path\to\file')
Notes: This version transforms csv into list of lists.
The 'rt' when opening the file is for reading in text mode.
Required: csv
Optional: from pprint import pprint
'''
import csv
print("Reading input file into memory")
# Initialize list
output = []
counter = 0
# Open file for reading in text mode
# If we encounter encoding errors use parameter 'encoding=utf-8'
# Alternatively 'encoding=ignore_errors'
f = open(input_csv, 'rt')
# Try block for reader
try:
reader = csv.reader(f, delimiter=',', quoting=csv.QUOTE_NONNUMERIC)
except:
return ("Error parsing csv file", -1)
else:
for row in reader:
output.append(row)
counter += 1
#print("row appended")
return (output, counter)
finally:
print("Read: " + str(counter) + "measurements into memory")
f.close()
def textfiletocsv(input_text, output_csv):
'''
'''
output = []
counter = 0
# Read the input file into a list
fin = open(input_text, "r")
data_list = fin.readlines()
fin.close()
fout = open(output_csv, 'w')
fout.writelines(data_list)
fout.close()
def extract_list_from_lol(list_in, location):
r"""
Name:
Function:
Input:
Output:
Notes:
Usage:
"""
#print("infunc")
#print(list_in)
#print(location)
print("Extracting list with index: " + str(location))
list_out = []
location_in = int(location)
for item in list_in:
#print(str(item) + "\n")
list_out.append(item[location_in])
return list_out
def script_params(string1):
'''
Function: script_params(string)
Description: Prints all the basic script parameters
Input: sys.argv[0]
Output: STDOUT print
Called as: script_params(sys.argv[0])
Notes: Always returns true
'''
import time
import sys
sname = str(string1)
sdir = str(sys.path[0])
sfpath = str(sys.path[0] + "\\" + string1)
print ('Script name : ' + string1)
print ('Script directory : ' + sys.path[0] )
print ('Script full path: ' + sys.path[0] + "\\" + string1)
print ("\n")
print ('Script started at: ' + time.strftime("%c") + "\n")
return(sname, sdir, sfpath)
def chck_args_num(var):
'''
Function : chck_args_num(var)
Description: Checks n. of variables
Input: Integer
Output: Boolean
Called as : chk_args(len(sys.argv))
'''
import sys
args_correct = 1
args_in = var
args_in_fixed = args_in - 1
if args_in_fixed != args_correct:
print ('Wrong number of arguments : ' + str(args_in_fixed))
print ('Must be : ' + str(args_correct))
return False
else:
print ('Correct number of arguments provided: ' + str(args_in_fixed) + "\n" )
return True
def script_path_param(string1):
# PUT IT INTO MODULE
#import sys
#import os
script_name = os.path.basename(string1)
script_dir = os.path.dirname(os.path.realpath(__file__)) + os.sep
script_full = script_dir + script_name
return ( script_name, script_dir, script_full )
def script_time_param():
# Name: time parameter
# Function: script_time_param
# Input: None
# Output: string with formatted time
# Usage: print (script_time_param) or a = script_time_param
return time.strftime("%c")
def chck_args_type(string):
'''
Function : chck_args_type(string)
Description: Checks the content of parameters
Input: sys.argv
Output: STDOUT print
Called as chck_args_type(sys.argv)
'''
for i in range(len(string)):
if i == 0:
print ("Script name: %s" % sys.argv[0])
else:
print ("%d. argument: %s" % (i,sys.argv[i]))
print ("\n")
return 0
# Parse arguments
# Checking n. of arguments
if not chck_args_num(len(sys.argv)):
print ('Terminating Script....')
sys.exit()
else:
file_in = sys.argv[1]
chck_args_type(sys.argv)
#file_ot = str(file_in) + datetime.now().strftime('%Y-%m-%d_%H-%M-%S') + "." + str(column_in) + ".pdf"
# Script Start
script_params(sys.argv[0])
print("Script: " + str(script_path_param(sys.argv[0])[0]) + " ran at: " + script_time_param() + " ")
# READ FILE_IN INTO LoL
list_data = csvtolist(file_in)[0]
#print(list_data)
list_data_line_length = len(list_data[0])
print(list_data_line_length)
ldln_fixed = list_data_line_length - 1
print(ldln_fixed)
for column_in in range(0, int(ldln_fixed), 1):
print("Processing column: " + str(column_in))
y_axis_data = extract_list_from_lol(list_data, column_in)
x_axis_data = np.arange(0, len(y_axis_data), 1)
file_ot = str(file_in) + datetime.now().strftime('%Y-%m-%d_%H-%M-%S') + "." + str(column_in) + ".pdf"
print("Output file: " + str(file_ot))
print("Plotting....")
# PLOT INTO FILE
fig=plt.figure(figsize=(4,3))
ax = fig.add_subplot(111)
ax.plot(x_axis_data, y_axis_data, label='Moment')
ax.set_xlabel('Time, s * 0.03')
ax.set_ylabel('Moment of Gyro, m/s')
ax.legend(loc='upper right', bbox_to_anchor=(1, -0.2))
ax.grid(True)
plt.savefig(file_ot, dpi=600, bbox_inches='tight')
plt.close()
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 30 16:56:00 2017
@author: P.Doulgeridis
"""
import os
import sys
import time
import csv
import numpy as np
import matplotlib.pyplot as plt
from datetime import datetime
file_in = sys.argv[1]
#file_in_other = sys.argv[2]
def csvtolist(input_csv):
'''
Name: csvtolistadv
Function: Converts an csv file into a list of lists
Each line of an csv file will be stored in a list, all such lists
will be stored in a central list [[line1][line2][line3]]
Input: /path/to/filename or sys.argv[1]
Output: List of Lists -> [[Field1;Field2][Field2;Field2]]
Usage: csvtolistoflists(r'\path\to\file')
Notes: This version transforms csv into list of lists.
The 'rt' when opening the file is for reading in text mode.
Required: csv
Optional: from pprint import pprint
'''
import csv
# Initialize list
output = []
counter = 0
# Open file for reading in text mode
# If we encounter encoding errors use parameter 'encoding=utf-8'
# Alternatively 'encoding=ignore_errors'
f = open(input_csv, 'rt')
# Try block for reader
try:
reader = csv.reader(f, delimiter=',', quoting=csv.QUOTE_NONNUMERIC)
except:
return ("Error parsing csv file", -1)
else:
for row in reader:
output.append(row)
counter += 1
#print("row appended")
return (output, counter)
finally:
f.close()
def textfiletocsv(input_text, output_csv):
'''
'''
output = []
counter = 0
# Read the input file into a list
fin = open(input_text, "r")
data_list = fin.readlines()
fin.close()
fout = open(output_csv, 'w')
fout.writelines(data_list)
fout.close()
def extract_list_from_lol(list_in, location):
r"""
Name:
Function:
Input:
Output:
Notes:
Usage:
"""
#print("infunc")
#print(list_in)
#print(location)
list_out = []
location_in = int(location)
for item in list_in:
#print(str(item) + "\n")
list_out.append(item[location_in])
return list_out
def script_params(string1):
'''
Function: script_params(string)
Description: Prints all the basic script parameters
Input: sys.argv[0]
Output: STDOUT print
Called as: script_params(sys.argv[0])
Notes: Always returns true
'''
import time
import sys
sname = str(string1)
sdir = str(sys.path[0])
sfpath = str(sys.path[0] + "\\" + string1)
print ('Script name : ' + string1)
print ('Script directory : ' + sys.path[0] )
print ('Script full path: ' + sys.path[0] + "\\" + string1)
print ("\n")
print ('Script started at: ' + time.strftime("%c") + "\n")
return(sname, sdir, sfpath)
def chck_args_num(var):
'''
Function : chck_args_num(var)
Description: Checks n. of variables
Input: Integer
Output: Boolean
Called as : chk_args(len(sys.argv))
'''
import sys
args_correct = 2
args_in = var
args_in_fixed = args_in - 1
if args_in_fixed != args_correct:
print ('Wrong number of arguments : ' + str(args_in_fixed))
print ('Must be : ' + str(args_correct))
return False
else:
print ('Correct number of arguments provided: ' + str(args_in_fixed) + "\n" )
return True
def script_path_param(string1):
# PUT IT INTO MODULE
#import sys
#import os
script_name = os.path.basename(string1)
script_dir = os.path.dirname(os.path.realpath(__file__)) + os.sep
script_full = script_dir + script_name
return ( script_name, script_dir, script_full )
def script_time_param():
# Name: time parameter
# Function: script_time_param
# Input: None
# Output: string with formatted time
# Usage: print (script_time_param) or a = script_time_param
return time.strftime("%c")
def chck_args_type(string):
'''
Function : chck_args_type(string)
Description: Checks the content of parameters
Input: sys.argv
Output: STDOUT print
Called as chck_args_type(sys.argv)
'''
for i in range(len(string)):
if i == 0:
print ("Script name: %s" % sys.argv[0])
else:
print ("%d. argument: %s" % (i,sys.argv[i]))
print ("\n")
return 0
# Parse arguments
# Checking n. of arguments
if not chck_args_num(len(sys.argv)):
print ('Terminating Script....')
sys.exit()
else:
file_in = sys.argv[1]
column_in = sys.argv[2]
chck_args_type(sys.argv)
file_ot = str(file_in) + datetime.now().strftime('%Y-%m-%d_%H-%M-%S') + "." + str(column_in) + ".pdf"
# Script Start
script_params(sys.argv[0])
print("Script: " + str(script_path_param(sys.argv[0])[0]) + " ran at: " + script_time_param() + " ")
# READ FILE_IN INTO LoL
list_data = csvtolist(file_in)
#print(list_data)
# EXTRACT LIST FROM LoL = column number
y_axis_data = extract_list_from_lol(list_data[0], column_in)
#print(y_axis_data)
x_axis_data = np.arange(0, len(y_axis_data), 1)
#print(x_axis_data)
# PLOT INTO FILE
fig=plt.figure(figsize=(4,3))
ax = fig.add_subplot(111)
ax.plot(x_axis_data, y_axis_data, label='Moment')
ax.set_xlabel('Time, s * 0.03')
ax.set_ylabel('Moment of Gyro, m/s')
ax.legend(loc='upper right', bbox_to_anchor=(1, -0.2))
ax.grid(True)
plt.savefig(file_ot, dpi=600, bbox_inches='tight')
plt.close()
# Script end
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 30 16:56:00 2017
@author: P.Doulgeridis
"""
import os
import sys
import time
import csv
import numpy as np
import matplotlib.pyplot as plt
from datetime import datetime
#file_in = sys.argv[1]
def csv_weird_to_list(input_csv):
output = []
counter = 0
# Read the input file in as a list
fin = open(input_csv, "r")
data_list = fin.readlines()
fin.close()
del data_list[:5]
fout = open('fixed.other.csv', 'w')
fout.writelines(data_list)
fout.close()
f = open('fixed.other.csv', 'rt')
try:
reader = csv.reader(f, delimiter=',' ,quoting=csv.QUOTE_NONNUMERIC)
except:
return("Errror parsing csv file", -1)
else:
for row in reader:
output.append(row)
counter+=1
return (output, counter)
finally:
f.close()
def textfiletocsv(input_text, output_csv):
'''
'''
output = []
counter = 0
# Read the input file into a list
fin = open(input_text, "r")
data_list = fin.readlines()
fin.close()
fout = open(output_csv, 'w')
fout.writelines(data_list)
fout.close()
def extract_list_from_lol(list_in, location):
r"""
Name:
Function:
Input:
Output:
Notes:
Usage:
"""
#print("infunc")
#print(list_in)
#print(location)
print("Extracting list with index: " + str(location))
list_out = []
location_in = int(location)
for item in list_in:
#print(str(item) + "\n")
list_out.append(item[location_in])
return list_out
def script_params(string1):
'''
Function: script_params(string)
Description: Prints all the basic script parameters
Input: sys.argv[0]
Output: STDOUT print
Called as: script_params(sys.argv[0])
Notes: Always returns true
'''
import time
import sys
sname = str(string1)
sdir = str(sys.path[0])
sfpath = str(sys.path[0] + "\\" + string1)
print ('Script name : ' + string1)
print ('Script directory : ' + sys.path[0] )
print ('Script full path: ' + sys.path[0] + "\\" + string1)
print ("\n")
print ('Script started at: ' + time.strftime("%c") + "\n")
return(sname, sdir, sfpath)
def chck_args_num(var):
'''
Function : chck_args_num(var)
Description: Checks n. of variables
Input: Integer
Output: Boolean
Called as : chk_args(len(sys.argv))
'''
import sys
args_correct = 1
args_in = var
args_in_fixed = args_in - 1
if args_in_fixed != args_correct:
print ('Wrong number of arguments : ' + str(args_in_fixed))
print ('Must be : ' + str(args_correct))
return False
else:
print ('Correct number of arguments provided: ' + str(args_in_fixed) + "\n" )
return True
def script_path_param(string1):
# PUT IT INTO MODULE
#import sys
#import os
script_name = os.path.basename(string1)
script_dir = os.path.dirname(os.path.realpath(__file__)) + os.sep
script_full = script_dir + script_name
return ( script_name, script_dir, script_full )
def script_time_param():
# Name: time parameter
# Function: script_time_param
# Input: None
# Output: string with formatted time
# Usage: print (script_time_param) or a = script_time_param
return time.strftime("%c")
def chck_args_type(string):
'''
Function : chck_args_type(string)
Description: Checks the content of parameters
Input: sys.argv
Output: STDOUT print
Called as chck_args_type(sys.argv)
'''
for i in range(len(string)):
if i == 0:
print ("Script name: %s" % sys.argv[0])
else:
print ("%d. argument: %s" % (i,sys.argv[i]))
print ("\n")
return 0
# Parse arguments
# Checking n. of arguments
if not chck_args_num(len(sys.argv)):
print ('Terminating Script....')
sys.exit()
else:
file_in = sys.argv[1]
chck_args_type(sys.argv)
#file_ot = str(file_in) + datetime.now().strftime('%Y-%m-%d_%H-%M-%S') + "." + str(column_in) + ".pdf"
# Script Start
script_params(sys.argv[0])
print("Script: " + str(script_path_param(sys.argv[0])[0]) + " ran at: " + script_time_param() + " ")
# READ FILE_IN INTO LoL
list_data = csv_weird_to_list(file_in)[0]
#print(list_data)
list_data_line_length = len(list_data[0])
print(list_data_line_length)
ldln_fixed = list_data_line_length - 1
print(ldln_fixed)
for column_in in range(0, int(ldln_fixed), 1):
print("Processing column: " + str(column_in))
y_axis_data = extract_list_from_lol(list_data, column_in)
x_axis_data = np.arange(0, len(y_axis_data), 1)
file_ot = str(file_in) + datetime.now().strftime('%Y-%m-%d_%H-%M-%S') + "." + str(column_in) + ".pdf"
print("Output file: " + str(file_ot))
print("Plotting....")
# PLOT INTO FILE
fig=plt.figure(figsize=(4,3))
ax = fig.add_subplot(111)
ax.plot(x_axis_data, y_axis_data, label='Moment')
ax.set_xlabel('Time, s * 0.03')
ax.set_ylabel('Moment of Gyro, m/s')
ax.legend(loc='upper right', bbox_to_anchor=(1, -0.2))
ax.grid(True)
plt.savefig(file_ot, dpi=600, bbox_inches='tight')
plt.close()
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 30 16:56:00 2017
@author: P.Doulgeridis
"""
import os
import sys
import time
import csv
import numpy as np
import matplotlib.pyplot as plt
from datetime import datetime
file_in = sys.argv[1]
#file_in_other = sys.argv[2]
def csv_weird_to_list(input_csv):
output = []
counter = 0
# Read the input file in as a list
fin = open(input_csv, "r")
data_list = fin.readlines()
fin.close()
del data_list[:5]
fout = open('fixed.other.csv', 'w')
fout.writelines(data_list)
fout.close()
f = open('fixed.other.csv', 'rt')
try:
reader = csv.reader(f, delimiter=',' ,quoting=csv.QUOTE_NONNUMERIC)
except:
return("Errror parsing csv file", -1)
else:
for row in reader:
output.append(row)
counter+=1
return (output, counter)
finally:
f.close()
def textfiletocsv(input_text, output_csv):
'''
'''
output = []
counter = 0
# Read the input file into a list
fin = open(input_text, "r")
data_list = fin.readlines()
fin.close()
fout = open(output_csv, 'w')
fout.writelines(data_list)
fout.close()
def extract_list_from_lol(list_in, location):
r"""
Name:
Function:
Input:
Output:
Notes:
Usage:
"""
#print("infunc")
#print(list_in)
#print(location)
list_out = []
location_in = int(location)
for item in list_in:
#print(str(item) + "\n")
list_out.append(item[location_in])
return list_out
def script_params(string1):
'''
Function: script_params(string)
Description: Prints all the basic script parameters
Input: sys.argv[0]
Output: STDOUT print
Called as: script_params(sys.argv[0])
Notes: Always returns true
'''
import time
import sys
sname = str(string1)
sdir = str(sys.path[0])
sfpath = str(sys.path[0] + "\\" + string1)
print ('Script name : ' + string1)
print ('Script directory : ' + sys.path[0] )
print ('Script full path: ' + sys.path[0] + "\\" + string1)
print ("\n")
print ('Script started at: ' + time.strftime("%c") + "\n")
return(sname, sdir, sfpath)
def chck_args_num(var):
'''
Function : chck_args_num(var)
Description: Checks n. of variables
Input: Integer
Output: Boolean
Called as : chk_args(len(sys.argv))
'''
import sys
args_correct = 2
args_in = var
args_in_fixed = args_in - 1
if args_in_fixed != args_correct:
print ('Wrong number of arguments : ' + str(args_in_fixed))
print ('Must be : ' + str(args_correct))
return False
else:
print ('Correct number of arguments provided: ' + str(args_in_fixed) + "\n" )
return True
def script_path_param(string1):
# PUT IT INTO MODULE
#import sys
#import os
script_name = os.path.basename(string1)
script_dir = os.path.dirname(os.path.realpath(__file__)) + os.sep
script_full = script_dir + script_name
return ( script_name, script_dir, script_full )
def script_time_param():
# Name: time parameter
# Function: script_time_param
# Input: None
# Output: string with formatted time
# Usage: print (script_time_param) or a = script_time_param
return time.strftime("%c")
def chck_args_type(string):
'''
Function : chck_args_type(string)
Description: Checks the content of parameters
Input: sys.argv
Output: STDOUT print
Called as chck_args_type(sys.argv)
'''
for i in range(len(string)):
if i == 0:
print ("Script name: %s" % sys.argv[0])
else:
print ("%d. argument: %s" % (i,sys.argv[i]))
print ("\n")
return 0
# Parse arguments
# Checking n. of arguments
if not chck_args_num(len(sys.argv)):
print ('Terminating Script....')
sys.exit()
else:
file_in = sys.argv[1]
column_in = sys.argv[2]
chck_args_type(sys.argv)
file_ot = str(file_in) + datetime.now().strftime('%Y-%m-%d_%H-%M-%S') + "." + str(column_in) + ".pdf"
# Script Start
script_params(sys.argv[0])
print("Script: " + str(script_path_param(sys.argv[0])[0]) + " ran at: " + script_time_param() + " ")
# READ FILE_IN INTO LoL
list_data = csv_weird_to_list(file_in)
#print(list_data)
# EXTRACT LIST FROM LoL = column number
y_axis_data = extract_list_from_lol(list_data[0], column_in)
#print(y_axis_data)
x_axis_data = np.arange(0, len(y_axis_data), 1)
#print(x_axis_data)
# PLOT INTO FILE
fig=plt.figure(figsize=(8,7))
ax = fig.add_subplot(111)
ax.plot(x_axis_data, y_axis_data, label='Moment')
ax.set_xlabel('Time, s * 0.03')
ax.set_ylabel('Moment of Gyro, m/s')
ax.legend(loc='upper right', bbox_to_anchor=(1, -0.2))
ax.grid(True)
plt.savefig(file_ot, dpi=600, bbox_inches='tight')
plt.close()
# Script end
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 30 16:56:00 2017
@author: P.Doulgeridis
"""
import os
import sys
import time
import csv
import numpy as np
import matplotlib.pyplot as plt
from datetime import datetime
#file_in = sys.argv[1]
def csvtolist(input_csv):
'''
Name: csvtolistadv
Function: Converts an csv file into a list of lists
Each line of an csv file will be stored in a list, all such lists
will be stored in a central list [[line1][line2][line3]]
Input: /path/to/filename or sys.argv[1]
Output: List of Lists -> [[Field1;Field2][Field2;Field2]]
Usage: csvtolistoflists(r'\path\to\file')
Notes: This version transforms csv into list of lists.
The 'rt' when opening the file is for reading in text mode.
Required: csv
Optional: from pprint import pprint
'''
import csv
print("Reading input file into memory")
# Initialize list
output = []
counter = 0
# Open file for reading in text mode
# If we encounter encoding errors use parameter 'encoding=utf-8'
# Alternatively 'encoding=ignore_errors'
f = open(input_csv, 'rt')
# Try block for reader
try:
reader = csv.reader(f, delimiter=',', quoting=csv.QUOTE_NONNUMERIC)
except:
return ("Error parsing csv file", -1)
else:
for row in reader:
output.append(row)
counter += 1
#print("row appended")
return (output, counter)
finally:
print("Read: " + str(counter) + "measurements into memory")
f.close()
def textfiletocsv(input_text, output_csv):
'''
'''
output = []
counter = 0
# Read the input file into a list
fin = open(input_text, "r")
data_list = fin.readlines()
fin.close()
fout = open(output_csv, 'w')
fout.writelines(data_list)
fout.close()
def extract_list_from_lol(list_in, location):
r"""
Name:
Function:
Input:
Output:
Notes:
Usage:
"""
#print("infunc")
#print(list_in)
#print(location)
print("Extracting list with index: " + str(location))
list_out = []
location_in = int(location)
for item in list_in:
#print(str(item) + "\n")
list_out.append(item[location_in])
return list_out
def script_params(string1):
'''
Function: script_params(string)
Description: Prints all the basic script parameters
Input: sys.argv[0]
Output: STDOUT print
Called as: script_params(sys.argv[0])
Notes: Always returns true
'''
import time
import sys
sname = str(string1)
sdir = str(sys.path[0])
sfpath = str(sys.path[0] + "\\" + string1)
print ('Script name : ' + string1)
print ('Script directory : ' + sys.path[0] )
print ('Script full path: ' + sys.path[0] + "\\" + string1)
print ("\n")
print ('Script started at: ' + time.strftime("%c") + "\n")
return(sname, sdir, sfpath)
def chck_args_num(var):
'''
Function : chck_args_num(var)
Description: Checks n. of variables
Input: Integer
Output: Boolean
Called as : chk_args(len(sys.argv))
'''
import sys
args_correct = 1
args_in = var
args_in_fixed = args_in - 1
if args_in_fixed != args_correct:
print ('Wrong number of arguments : ' + str(args_in_fixed))
print ('Must be : ' + str(args_correct))
return False
else:
print ('Correct number of arguments provided: ' + str(args_in_fixed) + "\n" )
return True
def script_path_param(string1):
# PUT IT INTO MODULE
#import sys
#import os
script_name = os.path.basename(string1)
script_dir = os.path.dirname(os.path.realpath(__file__)) + os.sep
script_full = script_dir + script_name
return ( script_name, script_dir, script_full )
def script_time_param():
# Name: time parameter
# Function: script_time_param
# Input: None
# Output: string with formatted time
# Usage: print (script_time_param) or a = script_time_param
return time.strftime("%c")
def chck_args_type(string):
'''
Function : chck_args_type(string)
Description: Checks the content of parameters
Input: sys.argv
Output: STDOUT print
Called as chck_args_type(sys.argv)
'''
for i in range(len(string)):
if i == 0:
print ("Script name: %s" % sys.argv[0])
else:
print ("%d. argument: %s" % (i,sys.argv[i]))
print ("\n")
return 0
# Parse arguments
# Checking n. of arguments
if not chck_args_num(len(sys.argv)):
print ('Terminating Script....')
sys.exit()
else:
file_in = sys.argv[1]
chck_args_type(sys.argv)
#file_ot = str(file_in) + datetime.now().strftime('%Y-%m-%d_%H-%M-%S') + "." + str(column_in) + ".pdf"
# Script Start
script_params(sys.argv[0])
print("Script: " + str(script_path_param(sys.argv[0])[0]) + " ran at: " + script_time_param() + " ")
# READ FILE_IN INTO LoL
list_data = csvtolist(file_in)[0]
#print(list_data)
list_data_line_length = len(list_data[0])
print(list_data_line_length)
ldln_fixed = list_data_line_length - 1
print(ldln_fixed)
for column_in in range(0, int(ldln_fixed), 1):
print("Processing column: " + str(column_in))
y_axis_data = extract_list_from_lol(list_data, column_in)
x_axis_data = np.arange(0, len(y_axis_data), 1)
file_ot = str(file_in) + datetime.now().strftime('%Y-%m-%d_%H-%M-%S') + "." + str(column_in) + ".pdf"
print("Output file: " + str(file_ot))
print("Plotting....")
# PLOT INTO FILE
fig=plt.figure(figsize=(4,3))
ax = fig.add_subplot(111)
ax.plot(x_axis_data, y_axis_data, label='Moment')
ax.set_xlabel('Time, s * 0.03')
ax.set_ylabel('Moment of Gyro, m/s')
ax.legend(loc='upper right', bbox_to_anchor=(1, -0.2))
ax.grid(True)
plt.savefig(file_ot, dpi=600, bbox_inches='tight')
plt.close()
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 30 16:56:00 2017
@author: P.Doulgeridis
"""
import os
import sys
import time
import csv
import numpy as np
import matplotlib.pyplot as plt
from datetime import datetime
file_in = sys.argv[1]
#file_in_other = sys.argv[2]
def csvtolist(input_csv):
'''
Name: csvtolistadv
Function: Converts an csv file into a list of lists
Each line of an csv file will be stored in a list, all such lists
will be stored in a central list [[line1][line2][line3]]
Input: /path/to/filename or sys.argv[1]
Output: List of Lists -> [[Field1;Field2][Field2;Field2]]
Usage: csvtolistoflists(r'\path\to\file')
Notes: This version transforms csv into list of lists.
The 'rt' when opening the file is for reading in text mode.
Required: csv
Optional: from pprint import pprint
'''
import csv
# Initialize list
output = []
counter = 0
# Open file for reading in text mode
# If we encounter encoding errors use parameter 'encoding=utf-8'
# Alternatively 'encoding=ignore_errors'
f = open(input_csv, 'rt')
# Try block for reader
try:
reader = csv.reader(f, delimiter=',', quoting=csv.QUOTE_NONNUMERIC)
except:
return ("Error parsing csv file", -1)
else:
for row in reader:
output.append(row)
counter += 1
#print("row appended")
return (output, counter)
finally:
f.close()
def textfiletocsv(input_text, output_csv):
'''
'''
output = []
counter = 0
# Read the input file into a list
fin = open(input_text, "r")
data_list = fin.readlines()
fin.close()
fout = open(output_csv, 'w')
fout.writelines(data_list)
fout.close()
def extract_list_from_lol(list_in, location):
r"""
Name:
Function:
Input:
Output:
Notes:
Usage:
"""
print("infunc")
print(list_in)
print(location)
list_out = []
location_in = int(location)
for item in list_in:
print(str(item) + "\n")
list_out.append(item[location_in])
return list_out
def script_params(string1):
'''
Function: script_params(string)
Description: Prints all the basic script parameters
Input: sys.argv[0]
Output: STDOUT print
Called as: script_params(sys.argv[0])
Notes: Always returns true
'''
import time
import sys
sname = str(string1)
sdir = str(sys.path[0])
sfpath = str(sys.path[0] + "\\" + string1)
print ('Script name : ' + string1)
print ('Script directory : ' + sys.path[0] )
print ('Script full path: ' + sys.path[0] + "\\" + string1)
print ("\n")
print ('Script started at: ' + time.strftime("%c") + "\n")
return(sname, sdir, sfpath)
def chck_args_num(var):
'''
Function : chck_args_num(var)
Description: Checks n. of variables
Input: Integer
Output: Boolean
Called as : chk_args(len(sys.argv))
'''
import sys
args_correct = 2
args_in = var
args_in_fixed = args_in - 1
if args_in_fixed != args_correct:
print ('Wrong number of arguments : ' + str(args_in_fixed))
print ('Must be : ' + str(args_correct))
return False
else:
print ('Correct number of arguments provided: ' + str(args_in_fixed) + "\n" )
return True
def script_path_param(string1):
# PUT IT INTO MODULE
#import sys
#import os
script_name = os.path.basename(string1)
script_dir = os.path.dirname(os.path.realpath(__file__)) + os.sep
script_full = script_dir + script_name
return ( script_name, script_dir, script_full )
def script_time_param():
# Name: time parameter
# Function: script_time_param
# Input: None
# Output: string with formatted time
# Usage: print (script_time_param) or a = script_time_param
return time.strftime("%c")
def chck_args_type(string):
'''
Function : chck_args_type(string)
Description: Checks the content of parameters
Input: sys.argv
Output: STDOUT print
Called as chck_args_type(sys.argv)
'''
for i in range(len(string)):
if i == 0:
print ("Script name: %s" % sys.argv[0])
else:
print ("%d. argument: %s" % (i,sys.argv[i]))
print ("\n")
return 0
# Parse arguments
# Checking n. of arguments
if not chck_args_num(len(sys.argv)):
print ('Terminating Script....')
sys.exit()
else:
file_in = sys.argv[1]
column_in = sys.argv[2]
chck_args_type(sys.argv)
file_ot = str(file_in) + datetime.now().strftime('%Y-%m-%d_%H-%M-%S') + ".pdf"
# Script Start
script_params(sys.argv[0])
print("Script: " + str(script_path_param(sys.argv[0])[0]) + " ran at: " + script_time_param() + " ")
# READ FILE_IN INTO LoL
list_data = csvtolist(file_in)
print(list_data)
# EXTRACT LIST FROM LoL = column number
y_axis_data = extract_list_from_lol(list_data[0], column_in)
z_axis_data = extract_list_from_lol(list_data[0], (int(column_in) + 1))
f_axis_data = extract_list_from_lol(list_data[0], (int(column_in) + 2))
print(y_axis_data)
x_axis_data = np.arange(0, len(y_axis_data), 1)
print(x_axis_data)
# PLOT INTO FILE
fig=plt.figure(figsize=(4,3))
ax = fig.add_subplot(111)
ax.plot(x_axis_data, y_axis_data, label='Moment')
ax.plot(x_axis_data, z_axis_data, label='This')
ax.plot(x_axis_data, f_axis_data, label='This')
ax.set_xlabel('Time, s * 0.03')
ax.set_ylabel('Moment of Gyro, m/s')
ax.legend(loc='upper right', bbox_to_anchor=(1, -0.2))
ax.grid(True)
plt.savefig(file_ot, dpi=600, bbox_inches='tight')
plt.close()
# Script end
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 30 16:56:00 2017
@author: P.Doulgeridis
"""
import os
import sys
import time
import csv
import numpy as np
import matplotlib.pyplot as plt
file_in = sys.argv[1]
#file_in_other = sys.argv[2]
def csvtolist(input_csv):
'''
Name: csvtolistadv
Function: Converts an csv file into a list of lists
Each line of an csv file will be stored in a list, all such lists
will be stored in a central list [[line1][line2][line3]]
Input: /path/to/filename or sys.argv[1]
Output: List of Lists -> [[Field1;Field2][Field2;Field2]]
Usage: csvtolistoflists(r'\path\to\file')
Notes: This version transforms csv into list of lists.
The 'rt' when opening the file is for reading in text mode.
Required: csv
Optional: from pprint import pprint
'''
import csv
# Initialize list
output = []
counter = 0
# Open file for reading in text mode
# If we encounter encoding errors use parameter 'encoding=utf-8'
# Alternatively 'encoding=ignore_errors'
f = open(input_csv, 'rt')
# Try block for reader
try:
reader = csv.reader(f, delimiter=',', quoting=csv.QUOTE_NONNUMERIC)
except:
return ("Error parsing csv file", -1)
else:
for row in reader:
output.append(row)
counter += 1
#print("row appended")
return (output, counter)
finally:
f.close()
def textfiletocsv(input_text, output_csv):
'''
'''
output = []
counter = 0
# Read the input file into a list
fin = open(input_text, "r")
data_list = fin.readlines()
fin.close()
fout = open(output_csv, 'w')
fout.writelines(data_list)
fout.close()
def extract_list_from_lol(list_in, location):
r"""
Name:
Function:
Input:
Output:
Notes:
Usage:
"""
print("infunc")
print(list_in)
print(location)
list_out = []
location_in = int(location)
for item in list_in:
print(str(item) + "\n")
list_out.append(item[location_in])
return list_out
# Variables
# Functions
# Parse arguments
# FILE_IN
file_in = sys.argv[1]
column_in = sys.argv[2]
# COLUMN_NUMBER
# Script Start
# READ FILE_IN INTO LoL
list_data = csvtolist(file_in)
print(list_data)
# EXTRACT LIST FROM LoL = column number
y_axis_data = extract_list_from_lol(list_data[0], column_in)
print(y_axis_data)
x_axis_data = np.arange(0, len(y_axis_data), 1)
print(x_axis_data)
# PLOT INTO FILE
fig=plt.figure(figsize=(4,3))
ax = fig.add_subplot(111)
ax.plot(x_axis_data, y_axis_data, label='Moment')
ax.set_xlabel('Time, s * 0.03')
ax.set_ylabel('Moment of Gyro, m/s')
ax.legend(loc='upper right', bbox_to_anchor=(1, -0.2))
ax.grid(True)
plt.savefig('MomentofGyro3.pdf', dpi=600, bbox_inches='tight')
plt.close()
# Script end
# -*- coding: utf-8 -*-
"""
Created on Sun Jan 29 13:56:22 2017
@author: panagos
"""
##########################################
# CUSTOMIZATION
import matplotlib.pyplot as plt
import numpy as np
# GOOD FOR MONITORING SPREAD OF ONE VARIABLE
# FOR TWO VARIABLES USE SCATTER OR LINE
# Preset colors for each value
col = {
1:'red',
2:'green',
3:'blue',
4:'yellow',
5:'black'
}
# Declare the two sets of data
# Data will be correlated like a,b were numpy arrays
a = [1, 20, 31, 2, 3, 4, 5, 1, 6, 4, 3, 2, 1, 2, 3, 4, 5, 40, 40, 3, 4, 5, 1]
b = [3, 9, 2, 6, 5, 6, 3, 4, 5, 3, 3, 2, 3, 4, 5, 3, 4, 5, 3, 4, 5, 1, 3]
size = [ 5, 1, 3, 2, 3, 4, 5, 6, 3, 4, 5, 6, 3, 4, 5, 3, 2, 1, 2, 3, 4, 5, 3, 4, 6 ]
# Use numpy arrays to make size bigger
# THIS IS HOW WE GROW THE GROWTH RATE OF THE SCATTER POINTS
size = np.array(size)
np_size = 109 * size
# Call plt.plot(a,b for a line chart)
# a = x axis
# b = y axis
#plt.plot(a, b)
# Show chart
#plt.show()
# Call plt.scatter(a,b) for a scatter chart
#plt.scatter(a, b)
# Assign names to vars
xlab = "x-label"
ylab = "y-label"
gtitle = "graph title"
tick_val = [-10, 0, 10 ]
tick_lab = [ "Neg", "Start", "Ten"]
##############3
plt.scatter(a,b)
# Instead we could hardcore the strings in
#plt.xscale('log')
plt.xlabel(xlab)
plt.ylabel(ylab)
plt.title(gtitle)
plt.xticks([ -10, 0, 10 ], [ "Neg", "Start", "Ten"])
# Preset list input :
#plt.xticks(tick_val, tick_lab)
plt.show()
#####################
# SIZE PARAMETER TO SCATTER WILL MAKE THE SCATTER POINTS GROW ACCORDING TO SIZE
# CAN BE OMITTED
# USED FOR SCATTER BUBBLE CHARTS
# IF WE WANT TO CHANGE THE GROWTH OF THE SCATTER POINTS LOOK AT B - NUMPY ARRAY
# WITH ALPHA PARAMETER WE CHANGE OPACITY OF BUBBLES
plt.scatter(a,b, s = size, alpha = 0.1)
# Instead we could hardcore the strings in
#plt.xscale('log')
plt.xlabel(xlab)
plt.ylabel(ylab)
plt.title(gtitle)
plt.xticks([ -10, 0, 10 ], [ "Neg", "Start", "Ten"])
# Preset list input :
#plt.xticks(tick_val, tick_lab)
plt.show()
#####################
# BY CHANGING COLOR WE CHANGE THE COLLOR OF THE SCATTER POINTS
# DEFAULT IS BLUE
plt.scatter(a,b, s = np_size, color = 'green')
# Instead we could hardcore the strings in
#plt.xscale('log')
plt.xlabel(xlab)
plt.ylabel(ylab)
plt.title(gtitle)
plt.xticks([ -10, 0, 10 ], [ "Neg", "Start", "Ten"])
# with plt.txt we insert text over specific pair of points
plt.text(1, 3, 'TEXT')
plt.grid(True)
# Preset list input :
#plt.xticks(tick_val, tick_lab)
plt.show()
#######################
# Change the scale on x axis to logarithmic
#plt.xscale('log')
#plt.show
# DEFAULT IS 10
# Bins specifies the number of bins on the histogram
#plt.hist(a, bins = 5)
#plt.show()
#plt.hist(a, bins = 10)
#plt.show()
# Clears a histogram
#plt.clf()
#plt.hist(b)
#plt.show
# -*- coding: utf-8 -*-
"""
Created on Sun Jan 29 13:28:26 2017
@author: panagos
"""
import matplotlib.pyplot as plt
##########################################
# HISTOGRAM
# GOOD FOR MONITORING SPREAD OF ONE VARIABLE
# FOR TWO VARIABLES USE SCATTER OR LINE
# Declare the two sets of data
# Data will be correlated like a,b were numpy arrays
a = [1, 20, 31, 2, 3, 4, 5, 1, 6, 4, 3, 2, 1, 2, 3, 4, 5, 40, 40, 40 , 40 , 40 , 2, 3, 4, 1, 2, 3, 4, 6, 5, 3, 5, 6, 3, 4, 5]
b = [3, 9, 2, 6]
# Call plt.plot(a,b for a line chart)
# a = x axis
# b = y axis
#plt.plot(a, b)
# Show chart
#plt.show()
# Call plt.scatter(a,b) for a scatter chart
#plt.scatter(a, b)
# Change the scale on x axis to logarithmic
#plt.xscale('log')
#plt.show
# DEFAULT IS 10
# Bins specifies the number of bins on the histogram
plt.hist(a, bins = 5)
plt.show()
plt.hist(a, bins = 10)
plt.show()
# Clears a histogram
plt.clf()
#plt.hist(b)
#plt.show
# -*- coding: utf-8 -*-
"""
Created on Sun Jan 29 13:11:59 2017
@author: panagos
"""
import matplotlib.pyplot as plt
# Declare the two sets of data
# Data will be correlated like a,b were numpy arrays
a = [1, 2, 3, 4]
b = [3, 9, 2, 6]
# Call plt.plot(a,b for a line chart)
# a = x axis
# b = y axis
plt.plot(a, b)
# Show chart
plt.show()
# Call plt.scatter(a,b) for a scatter chart
plt.scatter(a, b)
# Change the scale on x axis to logarithmic
plt.xscale('log')
plt.show
1. matplotlibsimple
2. matplotlibhisto
3. matplotlibcustom
4. dataplot example1 (working)
5. dataplot example2 (working)
6. dataplot example3
7. dataplot example4
8. dataplot example5