I'm new to the world of python. I'm trying to create a plot showing accumulated GDD (Growing degree days) vs time for selected cities within a given period of time
I wrote a function to accomplish this, but I can't seem to get it to work right. I keep getting with an empty plot in it. Also a dimension error. Anyone know how i can solve these issues.
Any help/suggestions is appreciated!
Here is the code
import sys, argparse, csv
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import datetime as dt
def open_file(file_name, mode):
"""Open a file."""
try:
with open(sys.argv[1], 'r') as the_file:
filename=the_file.read()
except IOError as err:
print("Unable to open the file", file_name, "Ending program.\n", err)
input("\n\nPress the enter key to exit.")
sys.exit()
else:
return filename
"""Cities.txt file as an argument"""
try:
my_file = open_file(sys.argv[1], 'r')
except:
print("GDD needs one argument", "\nEnding program...\n")
input("Press the enter key to exit.")
sys.exit()
extension=".csv"
for line in my_file.splitlines():
file_name=line+extension
print(file_name)
with open('data/'+ file_name, "rU") as files:
val = list(csv.DictReader(files))
l = []
for i in range(0, len(val)):
row = val[i]
if row['Min Temp'] == '' or row['Max Temp'] == '':
pass
else:
GDD = ((float(row['Min Temp']) + float(row['Max Temp']))/2)-10
l.append(GDD)
val[i]['GDD'] = GDD
#print(row['Min Temp'], ' ' , row['Max Temp'], ' ', str(round(row['GDD'], 2)))
#plt.subplot(1,1,1)
#x = np.linspace(1, 12, 365, endpoint=True)
x = np.linspace(1, 12, 365, endpoint=True)
plt.plot(x,GDD, label = file_name.split(',')[0])
plt.gcf().autofmt_xdate()
plt.legend(loc="upper left")
plt.xlabel('Months', color='black')
plt.ylabel('Cumulative GDD (>10°C)')
plt.title('Accumulated Growing Degree Days')
plt.draw()
A simple and fast solution could be to add plt.hold(True) after a plot call.
A more clean solution is to use a figure which can bee seen as window which you draw onto. just like in this example
So you'd define a figure, keep its reference, add axes and perform all action on these axes
fig = plt.figure()
ax = fig.add_axes([0.1, 0.1, 0.4, 0.7])
ax.plot(...)
Related
Currently trying to pull up figures that go with a response, whenever I open the figure (plt.draw) it pans focus to the picture and the user has to click back to the terminal each time the picture is called. I am trying to get it where the figure is a background object (so it will open but it won't shift focus) or possibly manually shift the Foreground Window to the terminal or the file name the code is running on. Also trying to make it linux and windows friendly so can't be windows specific commands, but anything helps. My code is provided below:
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
import warnings
warnings.filterwarnings("ignore")
def ShowImageCommon(wintitle = "", imgpath = "", imgtitle = "", imgshowdelay = 5):
ImageAddress = imgpath
ImageItself = Image.open(ImageAddress)
ImageNumpyFormat = np.asarray(ImageItself)
plt.title(imgtitle)
figure = plt.gcf()
# figure.set_visible(not figure.get_visible())
figure.canvas.set_window_title(wintitle)
axis = plt.gca()
x_axis = axis.axes.get_xaxis()
x_axis.set_visible(False)
y_axis = axis.axes.get_yaxis()
y_axis.set_visible(False)
plt.show()
return ImageNumpyFormat
def ShowImageInteractive(wintitle = "", imgpath = "", imgtitle = "", imgpause = 0):
while True:
try:
ImageNumpyFormat = ShowImageCommon(wintitle, imgpath, imgtitle)
plt.imshow(ImageNumpyFormat)
plt.draw()
plt.pause(0.1) # Window closes after specified delay in sec
return plt
except:
imgpath = input(f'Could not open image path {imgpath}, please type path here >> ')
def main():
imgpause = 0.1
wintitle = 'UIB Functional Test'
imgpath = '{path to file}/Keypad Press Sequence.png'
imgtitle = 'Keypad Press Sequence'
plt = ShowImageInteractive(wintitle, imgpath, imgtitle, imgpause)
y_n= input("is this clear? >> ") # want focus back to terminal to answer question
if __name__ == "__main__":
main()
Also any suggestions for labeling windows and opening them are greatly appreciated but again, Linux friendly!
I'm running a script on a Raspberry Pi, where I pull some data from an accelerometer, and I want to continuously update a plot. I've read around and watched some youtube videos and I've decided for the Matplotlib animation.
Now everything kinda works but the plot doesn't really get drawn before I KeyboardInterrupt the script. And I see why, because the plot function is inside the loop. I've tried moving it out of the loop,but then it doesn't work at all.
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib import style
style.use("fivethirtyeight")
import time
import board
import busio
import adafruit_tca9548a
import adafruit_adxl34x
i2c = busio.I2C(board.SCL, board.SDA)
tca = adafruit_tca9548a.TCA9548A(i2c)
ad1 = adafruit_adxl34x.ADXL345(tca[0])
ad2 = adafruit_adxl34x.ADXL345(tca[2])
fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)
def animate(i):
G = []
while True:
x,y,z = ad2.acceleration
acc = [x,y,z]
acc_abs = [abs(a) for a in acc]
i = acc_abs.index(max(acc_abs))
stor = acc[i]
if stor>0:
stor = stor-10.52
elif stor<0:
stor = stor+10.52
time.sleep(1)
G.append(stor)
ax1.clear()
ax1.plot(G)
ani = animation.FuncAnimation(fig,animate,interval =1000)
plt.show()
How can I get matplotlib plots as emf or wmf files that are usable as vector graphics in MS Office (Word and PowerPoint)?
I've tried exporting to svg and converting to emf using both Inkscape and LibreOffice Draw, but both of those options seem to cause image quality loss resulting in raster images.
I've also tried exporting to pdf and converting to emf/wmf, but that has the same issue.
To save figures as .emf file in matplotlib using Linux, try the following:
Install Inkscape (I have installed Inkscape 0.92.4 in Ubuntu 16.04. Other versions should work alike)
In matplotlib, save the figure as .svg and then convert it to .emf via an Inkscape subprocess call.
For example:
import numpy as np
import subprocess
import matplotlib.pyplot as plt
x = np.arange(2,50,step=2)
y = x**2
plt.plot(x,y)
plt.savefig('y_is_x^2.svg', format='svg', bbox_inches='tight')
subprocess.call('inkscape y_is_x^2.svg -M y_is_x^2.emf',shell=True)
You can then insert the .emf figure as a picture in MS Word or PowerPoint. The quality is near .svg. Be warned though, large .svg files may not work.
Here is my solution to create WMF and SVG. You can install Inkscape and use the following class, 'SaveAndClosePlot' creates SVG and then by using the Inkscape it converted to WMF. TestPlot function can be customized for your need.
import os
from pathlib import Path
from ConfigParserM import logging
import subprocess
from matplotlib import pyplot as plt
class SVG_WMF_Plot:
def __init__(self):
self.__folderNameGraph = 'Graphs'
self.__WMF_SVGSaving = True
self.__inkScapePath = "C://Program Files//inkscape//inkscape.exe"
self.__figureDPI = 500
def getRootDirectory(self):
try:
return Path(os.path.dirname(os.path.realpath('__file__')))
except Exception as e:
logging.exception(e)
raise
def getAddressTo(self, Main=None, FolderName=None, FileName=None, Extension=None):
try:
if Main is None:
Main = self.getRootDirectory()
if FolderName:
Path1 = Path(Main) / Path(FolderName)
else:
Path1 = Path(Main)
if not os.path.exists(Path1):
os.makedirs(Path1)
if FileName:
if Extension:
File_Address = Path1 / Path(FileName + "." + Extension)
else:
File_Address = Path1 / Path(FileName)
else:
File_Address = Path1
return File_Address
except Exception as e:
logging.exception(e)
raise
def TestPlot(self):
try:
fig, ax1 = plt.subplots()
x = [1, 2]
y = [1, 2]
F1 = 'test'
ax1.plot(x, y)
self.SaveAndClosePlot(folderName=self.__folderNameGraph, fileName=F1)
except Exception as e:
logging.exception(e)
raise
def SaveAndClosePlot(self, folderName, fileName):
try:
Address = self.getAddressTo(FolderName=self.__folderNameGraph + f"\{folderName}", FileName=fileName, Extension="jpg")
plt.savefig(Address, format='jpg', dpi=self.__figureDPI, bbox_inches='tight')
if self.__WMF_SVGSaving:
Address = self.getAddressTo(FolderName=self.__folderNameGraph + f"\{folderName}", FileName=fileName, Extension="svg")
plt.savefig(Address, format='svg', dpi=self.__figureDPI, bbox_inches='tight')
# add removing SVG if needed
AddressWMF = self.getAddressTo(FolderName=self.__folderNameGraph + f"\{folderName}", FileName=fileName, Extension="wmf")
subprocess.call([self.__inkScapePath, str(Address.resolve()), '--export-wmf', str(AddressWMF.resolve())])
plt.clf()
plt.close()
except Exception as e:
logging.exception(e)
raise
I am trying the code below from the tutorial in youtube:
https://www.youtube.com/watch?v=83-_3x2AjXI&t=3s
Somehow the code gets stuck at the line:
source_code = urllib.request.urlopen(stock_price_url).read().decode()
Nothing happens, and I don't get any error message.
I have also tested the url address on the browser:
http://chartapi.finance.yahoo.com/instrument/1.0/TSLA/chartdata;type=quote;range=10y/csv
and it works fine.
I am using MacOS and python 3.5.2. Any suggestion? Maybe something wrong with my installation of python?
import matplotlib.pyplot as plt
import numpy as np
import urllib
import matplotlib.dates as mdates
def bytespdate2num(fmt, encoding='utf-8'):
strconverter = mdates.strpdate2num(fmt)
def bytesconverter(b):
s = b.decode(encoding)
return strconverter(s)
return bytesconverter
def graph_data(stock):
print("hello 10\n")
stock_price_url = 'http://chartapi.finance.yahoo.com/instrument/1.0/'+stock+'/chartdata;type=quote;range=10y/csv'
print("hello 11\n")
source_code = urllib.request.urlopen(stock_price_url).read().decode()
print("hello 12\n")
stock_data = []
split_source = source_code.split('\n')
print("hello 13\n")
for line in split_source:
split_line = line.split(',')
if len(split_line) == 6:
if 'values' not in line and 'labels' not in line:
stock_data.append(line)
date, closep, highp, lowp, openp, volume = np.loadtxt(stock_data,
delimiter=',',
unpack=True,
# %Y = full year. 2015
# %y = partial year 15
# %m = number month
# %d = number day
# %H = hours
# %M = minutes
# %S = seconds
# 12-06-2014
# %m-%d-%Y
converters={0: bytespdate2num('%Y%m%d')})
plt.plot_date(date, closep,'-', label='Price')
plt.xlabel('Date')
plt.ylabel('Price')
plt.title('Interesting Graph\nCheck it out')
plt.legend()
plt.show()
print("hello 3\n")
graph_data('TSLA')
I think you could add a timeout to urlopen
source_code = urllib.request.urlopen(stock_price_url, timeout=5).read().decode()
so that if the page is not responding back for longer than 5 minutes, the process will throw an error.
I am using the following Python script:
import numpy as np
import matplotlib.pyplot as plt
import nibabel
import os
def collapse_probtrack_results(waytotal_file, matrix_file):
with open(waytotal_file) as f:
waytotal = int(f.read())
data = nibabel.load(matrix_file).get_data()
collapsed = data.sum(axis=0) / waytotal * 100.
return collapsed
matrix_template = 'results/{roi}.nii.gz.probtrackx2/matrix_seeds_to_all_targets.nii.gz'
processed_seed_list = [s.replace('.nii.gz','').replace('label/', '')
for s in open('/home/salvatore/tirocinio/aal_rois_diff_space/aal.txt').read().split('\n')
if s]
N = len(processed_seed_list)
conn = np.zeros((N, N))
rois=[]
idx = 0
for roi in processed_seed_list:
matrix_file = template.format(roi=roi)
seed_directory = os.path.dirname(result)
roi = os.path.basename(seed_directory).replace('.nii.gz.probtrackx2', '')
waytotal_file = os.path.join(seed_directory, 'waytotal')
rois.append(roi)
try:
# if this particular seed hasn't finished processing, you can still
# build the matrix by catching OSErrors that pop up from trying
# to open the non-existent files
conn[idx, :] = collapse_probtrack_results(waytotal_file, matrix_file)
except OSError:
pass
idx += 1
# figure plotting
fig = plt.figure()
ax = fig.add_subplot(111)
cax = ax.matshow(conn, interpolation='nearest', )
cax.set_cmap('hot')
caxes = cax.get_axes()
When I try to run it I get the following error: NameError: name 'template' is not defined. This refers to line 22 of the script above. Can you please help me to figure out what is this about?
There is no variable like template, so template cannot be used in the right side of the expression. Try
matrix_file = matrix_template.format(roi=roi)
instead.