【发布时间】:2023-03-12 07:55:01
【问题描述】:
我有一个函数“plot_rdm”,它创建一个绘图并将其保存为“rdm.png”。我希望形成其中的几个图,每个图都使用不同的 .json 文件 - 所以我将函数 plot_rdm 保存在“plotrdm.py”中。
在 saverdm.py 文件中 - 我定义了要从中创建绘图的 .json 文件的文件路径,然后调用 plot_rdm 函数,循环遍历我要从中创建绘图的所有文件:
#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
带有plot_rdm函数的plotrdm.py文件如下:
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')
我可以单独创建图(即,当我不调用 plot_rdm 函数并循环文件但我每次都指定文件路径时)。但是当我使用以下代码时,我会在 AVIMA 文件夹中形成一个空图。我不确定 saverdm 文件有什么问题导致这种情况发生?
https://github.com/Taranks7/RDM_researchproject如果我还没有很好地解释发生了什么,这就是我正在做的项目。
谢谢
【问题讨论】:
标签: python loops for-loop matplotlib