I have a function 'plot_rdm', which creates a plot and saves it as 'rdm.png'. I want several of these plots to be formed, each using a different .json file - so I have the function plot_rdm saved in 'plotrdm.py'.
In the saverdm.py file - I defined the filepath of the .json file I want to create a plot from and then called the plot_rdm function, looping over all of the files I want to create a plot from:
#import libraries
import numpy as np
import matplotlib
import matplotlib.pyplot
import matplotlib.pyplot as plt
import scipy
import scipy.spatial
import scipy.spatial.distance as sd
from scipy.spatial.distance import squareform
import os
import json
# define fpath
#i.e. fpath[0] will be the first filepath...
path = './RDM_researchproject'
rootdir = path
filepath = []
for subdir, dirs, files in os.walk(rootdir):
for file in files:
if file.startswith('Meadows'):
count=0 # count default
filepath.append(os.path.join(subdir, file))
fpath = filepath[count]
os.system("/home/taran/RDM_researchproject/AVIMA/plotrdm.py")
count +=1
The plotrdm.py file with the plot_rdm function is as follows:
def plot_rdm(fpath):
import numpy as np
import matplotlib
import matplotlib.pyplot
import matplotlib.pyplot as plt
import scipy
import scipy.spatial
import scipy.spatial.distance as sd
from scipy.spatial.distance import squareform
import json
with open(fpath) as fhandle:
data = json.load(fhandle)
#inspect rdm stimuli labels
stim = data['stimuli']
#contain all labels for y axis and x axis seperately
y_names = []
for i in stim:
y_names.append(i['name'])
x_names = []
for i in stim:
x_names.append(i['name'])
#create rdm array and squareform
rdm_array = np.array(data['rdm'])
srdm = squareform(rdm_array)
#label x and y axis on rdm
fig, ax = plt.subplots()
rdm = ax.imshow(srdm)
ax.set_xticks(np.arange(len(x_names)))
ax.set_yticks(np.arange(len(y_names)))
ax.set_xticklabels(x_names)
ax.set_yticklabels(y_names)
plt.setp(ax.get_xticklabels(), rotation=90, ha="right", rotation_mode="anchor")
plt.plot(srdm)
plt.imshow(srdm)
plt.colorbar(mappable = None, cax = None, ax = None)
fig.subplots_adjust(bottom=0.23)
import matplotlib.pyplot as plt
plt.savefig('rdm.png')
I am able to create the plots individually (i.e. when I don't call the plot_rdm function and loop over the files but I specify the filepath each time). But when I use the following code, I get an empty plot forming in the AVIMA folder. I'm not sure what's wrong in the saverdm file making this happen?
https://github.com/Taranks7/RDM_researchproject If I haven't explained what's going on well, this is the project I'm working on.
Thank you
When you want to call a python function from another file, you should not try to run another python process by calling os.system. Just import that function:
from plotrdm import plot_rdm
Instead of using os.filewalk and a file.startswith check, we can cleanup the code a lot by using the nice python library glob. I throw in a enumerate for good measure.
Your new rdmsave.py
import glob
from plotrdm import plot_rdm
basedir = "."
if __name__ == "__main__":
count = 0
for count, path in enumerate(sorted(glob.glob(f'{basedir}/**/Meadow*.json', recursive=True)), start=1):
print(f"processing {path}")
output_image = f'rdm_{count - 1:02}.png'
print(f"output image will be {output_image}")
plot_rdm(path, output_image)
print(f"processed {count} files")
Note that you may need to change basedir back to your local path.
And your plotrdm.py becomes:
import numpy as np
import matplotlib
import matplotlib.pyplot
import matplotlib.pyplot as plt
import scipy
import scipy.spatial
import scipy.spatial.distance as sd
from scipy.spatial.distance import squareform
import json
import matplotlib.pyplot as plt
def plot_rdm(fpath, output_filename):
with open(fpath) as fhandle:
data = json.load(fhandle)
# inspect rdm stimuli labels
stim = data['stimuli']
# contain all labels for y axis and x axis seperately
y_names = []
for i in stim:
y_names.append(i['name'])
x_names = []
for i in stim:
x_names.append(i['name'])
# create rdm array and squareform
rdm_array = np.array(data['rdm'])
srdm = squareform(rdm_array)
# label x and y axis on rdm
fig, ax = plt.subplots()
rdm = ax.imshow(srdm)
ax.set_xticks(np.arange(len(x_names)))
ax.set_yticks(np.arange(len(y_names)))
ax.set_xticklabels(x_names)
ax.set_yticklabels(y_names)
plt.setp(ax.get_xticklabels(), rotation=90, ha="right", rotation_mode="anchor")
plt.plot(srdm)
plt.imshow(srdm)
plt.colorbar(mappable=None, cax=None, ax=None)
fig.subplots_adjust(bottom=0.23)
plt.savefig(output_filename)
I added the second argument output_filename to the plot_rdm function to make it possible to store each image in a new file.
The output on my machine reads
processing ./5/Meadows_avima-image-version1_v_v2_vital-macaw_2_tree.json
output image will be rdm_00.png
processing ./4/Meadows_avima-image-version1_v_v2_quick-louse_2_tree.json
output image will be rdm_01.png
processing ./1/Meadows_avima-image-version1_v_v2_better-hound_2_tree.json
output image will be rdm_02.png
processing ./3/Meadows_avima-image-version1_v_v2_huge-falcon_2_tree.json
output image will be rdm_03.png
processing ./2/Meadows_avima-image-version1_v_v2_guided-koi_2_tree.json
output image will be rdm_04.png
processed 4 files
And 4 png files are created in the current folder.
Related
I have plotted a graph for different sub-folders inside of a directory and I want to put a legend of each graph based on the name of the folder. I mean, the plot legend is being to be written according to the folder's name. The code for plotting is below:
from __future__ import division
import sys
import os
import numpy as np
import matplotlib.pyplot as plt
import glob
import seaborn as sns
from scipy import stats
from scipy.stats.kde import gaussian_kde
root = r'C:\Users\Hasan\Desktop\output\new our scenario\beta 15\test'
mean_cu=[]
my_list = os.listdir(root)
my_list = [file for file in my_list if os.path.isdir(os.path.join(root, file))]
for directory in my_list:
CASES = [file for file in os.listdir(os.path.join(root, directory)) if file.startswith('config')]
if len(CASES)==0:
continue
maxnum = np.max([int(os.path.splitext(f)[0].split('_')[1]) for f in CASES])
CASES = ['configuration_%d.out' % i for i in range(maxnum)]
mean_cu=[]
for i, d in enumerate(CASES):
a = np.loadtxt(os.path.join(root, directory,d)).T
num = os.path.splitext(d)[0]
local_cu = np.abs(a[4])
mean_curv.append(np.mean(local_cu))
pdf = stats.norm.pdf(mean_cu)
Time = np.arange(0,len(pdf))
plt.plot(Time,pdf)
From what I understand, you have different graphs, and for each of them you want a different legend based on current folder. You can set legend by adding label=directory in plot method. Maybe you should first extract current folder (using split or different method) if you don't want full directory. That depends on your directory variable.
Consider following example:
import matplotlib.pyplot as plt
import pandas as pd
legend1 = ["1", "2"]
df = pd.DataFrame({"A":[4,5], "B":[6,7]})
for item in legend1:
fig, ax = plt.subplots()
ax.plot(df["A"], df["B"], label=item)
ax.legend(loc='upper left', frameon=False)
will result the following two graphs:
As you can see the only different is the legend, that was set by legend1 list. You can make it your directories.
I've been trying to iterate over files in a folder and show them for two seconds each using this code:
import time
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.image import imread
import glob
import cv2
im = []
for filepath in glob.iglob(r'C:\Users\dan20\Pictures\wedding\beeri and adn. photo/*.jpg'):
a = imread(filepath)
b = cv2.resize(a, dsize = (456,304))
im += [b]
fig,ax = plt.subplots()
for i in im:
time.sleep(2)
ax.axis('off')
ax.imshow(i)
plt.show()
For some reason I can't see the images as long as i use time.sleep().
How can I make each picture to appear for N amount of times?
How about using plt.pause :
import numpy as np
from matplotlib import pyplot as plt
im = [np.random.random((9,9)) for i in range(1,6)]
fig,ax = plt.subplots()
for i in im:
ax.cla()
ax.imshow(i)
ax.axis('off')
plt.pause(2)
which gives :
I have a n amount of images with a format:
<PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=64x64 at 0x7F555F6E3898>
all together in a list.
I can visualize each individually but I want to visualize them all together, one beside another until it gets too long and then go to the next row (for instance, n/4 rows with 4 images in each row). Once this is done, I would like to save it as a jgp as well.
I tried using subplot from matplotlib but it says that the values are unhashable.
My code is:
from os import listdir
from os.path import isfile, join
files = [f for f in listdir(mypath) if isfile(join(mypath, f))]
files.sort()
files.sort(key = len)
im = []
for jpg in files:
im.append(Image.open(mypath+'/'+jpg))
for i in im:
image = np.asarray(i)
plt.subplot(3,np.floor(len(image)/3),image)
plt.show()
update your usage for subplot, then it should be good. please see below sample code.
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
# get sample data
from sklearn import datasets
x,y=datasets.load_digits(n_class=10, return_X_y=True)
x = x[0:100,:]
x = np.reshape(x,[100,8,8])
# plot
for i in range(x.shape[0]):
if i >= 9:
break
image = x[i,:].squeeze()
plt.subplot(3,3,i+1)
plt.imshow(image,cmap='gray',interpolation='none')
alternatively:
# https://matplotlib.org/mpl_toolkits/axes_grid/users/overview.html
from mpl_toolkits.axes_grid1 import ImageGrid
fig = plt.figure(1,(10,10))
grid = ImageGrid(fig, 111,
nrows_ncols=(2,7),
axes_pad=0.1,
)
for i in range(14):
image = x[i,:].squeeze()
grid[i].imshow(image,cmap='gray',interpolation='none')
I want to plot ECG graph using matplotlib . y values from a file having float values and x value is incrementing(ie x ranges from 1 to 1000). went through tutorials and couldn't find any solutions.
Demo Code
import numpy as np
import matplotlib.pyplot as plt
import random
import pickle
#Y Axis : Generate 1000 random numbers
yAxisNumbers = np.random.uniform(1,100,1000)
#Save numbers to a file for demo purpose
with open('numpyData.txt', 'wb') as myFile:
pickle.dump(yAxisNumbers,myFile)
#X Axis :Generate 1000 random numbers
xNumbers = [ x for x in range(1000)]
#Load file data to a list
with open('numpyData.txt', 'rb') as aFile:
yNumbers = pickle.load(aFile)
#Plot and label Graph
plt.plot(xNumbers,yNumbers)
plt.ylabel("Random Float Numbers")
plt.xlabel("Number Count")
plt.title("ECG Graph")
plt.show()
Graph
Here's a minimal answer, based on the scant details provided.
import numpy as np
import matplotlib.pyplot as plt
plt.ion()
Y = np.loadtxt(filename, other needed options)
plt.plot(np.arange(len(Y))+1,Y)
import numpy as np
import pylab as p
aa=np.loadtxt('....your file ....')
x,y= aa.T # transpose data into 2 columns, assuming you have 2 columns
p.plot(x,y)
p.show()
I'd like to use Matplotlib and pyplot to generate an svg image to be used in a Django framework. as of now I have it generating image files that are link to by the page, but is there a way to directly get with the svg image as a unicode string without having to write to the file system?
Try using StringIO to avoid writing any file-like object to disk.
import matplotlib.pyplot as plt
import StringIO
from matplotlib import numpy as np
x = np.arange(0,np.pi*3,.1)
y = np.sin(x)
fig = plt.figure()
plt.plot(x,y)
imgdata = StringIO.StringIO()
fig.savefig(imgdata, format='svg')
imgdata.seek(0) # rewind the data
svg_dta = imgdata.buf # this is svg data
file('test.htm', 'w').write(svg_dta) # test it
Here is python3 version
import matplotlib.pyplot as plt
import numpy as np
import io
f = io.BytesIO()
a = np.random.rand(10)
plt.bar(range(len(a)), a)
plt.savefig(f, format = "svg")
print(f.getvalue()) # svg string