# How to Plot Graphs Using Python Programming?

Python language to plot graph and read-write text and CSV file having 6 menus to perform different operations of calculations on temperatures and graphs.

# Programming Problem

A command line program is needed to show the user 6 options to carry out various tasks as detailed below. The program should allow the user to be able to select any of the options repeatedly as long as they don’t choose option 6 – which allows the user to exit the program. Each option is to be written as a python function, taking the necessary inputs if any from the user from the command line and the included files.

Option 1: Read file “input_data.txt” from the folder “data” into the program. Then remove duplicate and blank lines from this data. Then store this data as “input_formatted_data.txt” in folder “output”. If the folder is not present, create the folder.

## Solution:

import os
import csv
import string
import sys
import imp

def Main():

ans=True
while ans:
print (“””
1.Option 1 reading files
2.Option 2 merging files
3.Option 3 Sin wave graph
4.Option 4 temprature graph
5.Option 5 CSV Merging and graph plotting
6.Option 6 Exit/Quit
“””)
ans=raw_input(“Select option from menu? “)
if ans==”1″:

main = imp.load_source(‘Option1’, ‘Option1/Program.py’)
print(“\n Method called sucessfully”)
elif ans==”2″:
main = imp.load_source(‘Option2’, ‘Option2/Program.py’)
print(“\n Method called sucessfully”)
elif ans==”3″:
main = imp.load_source(‘Option3’, ‘Option3/Program.py’)
print(“\n Method called sucessfully”)
elif ans==”4″:
main = imp.load_source(‘Option4’, ‘Option4/Program.py’)
main.Main()
print(“\n Method called sucessfully”)
elif ans==”5″:
main = imp.load_source(‘Option5’, ‘Option5/Program.py’)
print(“\n Method called sucessfully”)
elif ans==”6″:
exit()
elif ans !=””:
print(“\n Not Valid Choice Try again”)

Main()

## Output:

Option 2: Read files “input_data2.txt” and “input_names.txt” from folder “data” and create a single file merging this data – “output_merged_data.txt”. Each line in the created file is to be unique based on the name (first column of each input file). So if the name is present in the both input files, the rest of the data has to be merged.

Example:

“input_data2.txt”                                            “input_names.txt”

John, 12.3, abcd                                              Adam, 121 station road, London

Johnny, 53.3, star                                           John, Brecon house, Pontypridd

Steve, 33.5, qwer

Output: “output_merged_data.txt”

John, 12.3, abcd, Brecon house, Pontypridd

Johnny, 53.3, star

Steve, 33.5, qwer

## Solution:

import os

lines=[“”]
all_Names=[“”]
def Main():
script_dir = os.path.dirname(__file__)
rel_path = “Data\input_data.txt”
abs_file_path = os.path.join(script_dir, rel_path)
rel_output = “output\input_formatted_data.txt”
rel_outputf = “output”
rel_folder = os.path.join(script_dir, rel_outputf)
out_file_path = os.path.join(script_dir, rel_output)

all_Names  = map(lambda s: s.strip(), all_Names)
all_Names  = list(set(all_Names))
all_Names = filter(None, all_Names)
if not os.path.exists(rel_folder):
os.makedirs(rel_folder)

if os.path.exists(out_file_path):
open(out_file_path, ‘w’).close()

else:
open(out_file_path, ‘w’)

file1 = open(out_file_path , “w”)
for item in all_Names:
file1.write(“%s\n” % item)
print(item)
file1.close()

stayWatch =  raw_input(‘Output folder have results :-‘)
Main()

## Output:

Option 3: Generate a sine wave of amplitude 2 at 50 Hz over 4 seconds. Then plot this on a graph with time on x axis and amplitude on y axis. Save this graph with title above the plot saying “sine wave – 50 Hz”, x axis label as “Time (s)” and x axis ticks every 0.5 second, y axis label as “Amplitude (V)” and y axis ticks every 0.4 v ranging from – 1.5 to 1.5V. Save this plot in the folder named “output” with the filename “<your first name>_sine_wave.png”.

## Solution:

import os
x = [“”]
lines=[“”]
Names=[“”]
def Main():
script_dir = os.path.dirname(__file__)
rel_path = “Data\input_data2.txt”
rel_names = “Data\input_name.txt”
rel_nameout = “output\output_merged_data.txt”
abs_file_path1 = os.path.join(script_dir, rel_path)
abs_file_path2 = os.path.join(script_dir, rel_names)

Names  = map(lambda s: s.strip(), Names)

Names = filter(None, Names)
lines  = map(lambda s: s.strip(), lines)

lines = filter(None, lines)
for i, val in enumerate(Names):
j= len(lines)
if (i < j):
linesstring = lines[i]
x2 = linesstring
k = x2.split(‘,’)
j = [k[0]] + [‘,’+l for l in k[1:]]
if(val.find(j[0])!=-1):

val = val.replace(j[0], linesstring)
x.append(val)
else:
x.append(val)
x.append(linesstring)
else:
x.append(val)
if os.path.exists(rel_nameout):
open(rel_nameout, ‘w’).close()

else:
open(rel_nameout, ‘w’)

file1 = open(rel_nameout , “w”)
for item in x:
file1.write(“%s\n” % item)
print(item)
file1.close()

stayWatch =  raw_input(‘output generated in output folder too :-‘)
Main()

## Output:

Option 4: Read files “input_temperature1.txt” and “input_temperature2.txt” to get the time and temperature recorded by two sensors in a room. Plot these as two lines with different colours in a graph [red, blue]. Also plot the average of the two sensors over time as another plot line in a different colour [green]. Add the legend, plot title as “temperature comparison plot”, x & y axis ticks and labels and save this in the folder named “output” with the filename “<your first name>_temperature_plot.png”.

“input_temperature1.txt”                              “input_temperature2.txt”

1          24.5                                                     1          23.4

2          24.2                                                     2          23.4

3          27.3                                                     3          18.9

….

50        25.2                                                     50        27.0

## Solution:

from numpy import sin, linspace, pi
from pylab import plot, show, title, xlabel, ylabel, subplot , savefig
from scipy import fft, arange

def plotSpectrum(y,Fs):

n = len(y) # length of the signal
k = arange(n)
T = n/Fs
frq = k/T
frq = frq[range(n/2)]

Y = fft(y)/n
Y = Y[range(n/2)]

plot(frq,abs(Y),’r’) # plotting the spectrum
xlabel(‘Freq (Hz)’)
ylabel(‘|Y(freq)|’)

Fs = 50.0;  # sampling rate
Ts = 2.0/Fs; # sampling interval
t = arange(0,1,Ts) # time vector

ff = 50;   # frequency of the signal
y = sin(2*pi*ff*t)

subplot(2,1,1)
plot(t,y)
xlabel(‘Time’)
ylabel(‘Amplitude’)
subplot(2,1,2)
plotSpectrum(y,Fs)
savefig(“output/_sine_wave.png”)
show()
print(“sin image saved in output folder:-“)

## Output:

Option 5: Read files “actualtemp.csv”, “set_temperature.csv” and “input_voltage.csv”. Combine these to a single file with one column as constant and the rest of the data from the files as additional columns and save this file to folder “output” under the name “combined_data.csv”. Then plot the data from “actualtemp.csv” and “set_temperature.csv” in a graph and save it as “temp_compare.png” in folder “output”. Add the legend, plot title as “temperature comparison plot”, x & y axis ticks and labels. Also plot the voltage as another graph and save it in the same folder as “voltage_plot.png”. Add the legend, plot title as “voltage plot”, x & y axis ticks and labels.

“actualtemp.csv”                    “set_temperature.csv”                       “input_voltage.csv”

1,23.4                                      1,25                                                     1, 4.75

2,24.2                                      2,25                                                     2,3.997

3,25.6                                      3,26                                                     3,4.001

50,24.4                                    50,23                                                   50,4.76

Output:

“combined_data.csv”

1,23.4,25,4.75

2,24.2,25,3.997

3,25.6,26,4.001

50,24.4,23,4.76

## Solution:

import os
import csv
import string
import sys
import matplotlib.pyplot as plt
import numpy as np

actual_temp = “”
actualt=[“”]
temperature2=[“”]
temperature=[“”]

a = [“”]
array = {}
script_dir = os.path.dirname(__file__)
actual_temp = ‘Data/input_temperature1.txt’
actual_temp2 = “Data/input_temperature2.txt”

actual_temp = os.path.join(script_dir, actual_temp)
actual_temp2 = os.path.join(script_dir, actual_temp2)

def Main():

with open(actual_temp) as f:
with open(actual_temp2) as f2:

xf = [float(i) for i in temperature]
print (xf)
yf = [float(i) for i in temperature2]
y = [int(i) for i in yf]
x = [int(i) for i in xf]
avg= (reduce(lambda x,y:x+y,x)/len(x))

plt.bar(x,y,align=’center’) # A bar chart
plt.xlabel(‘ticks’)
plt.ylabel(‘labels’)
plt.title(‘temperature comparison plot’)
for i in range(len(y)):
plt.hlines(y[i],0,x[i]) # Here you are drawing the horizontal lines
plt.plot(x, y, ‘r-‘)

plt.axvline(avg, color=’green’, linewidth=2)
plt.savefig(“output/firstname_temp_plot.png”)
plt.show()
print(“output image saved in output folder”)

Main()

SHARE