问题描述
我正在运行 Python v3.8.6。当我运行以下代码时,它可以工作。
def plot_timeseries(vars_to_plot,plt_config,plt_type=None):
if plt_config['ggplot']:
# Use ggplot style (grey background,white grid lines)
plt.style.use('ggplot')
# Use the first object in the list to parse common attributes.
years = calc_year_span(vars_to_plot[0].start_year,vars_to_plot[0].end_year)
units = vars_to_plot[0].units
var_short = vars_to_plot[0].short_name
var_long = getattr(Variables,var_short)['cesm_long_name']
# Iterate over the variable objects & plot.
if plt_type == 'diff':
# Model config difference plot.
diff_groups = group_vars_diff(vars_to_plot)
for idx,(dataset,var_dict) in enumerate(diff_groups.items()):
# Diff = perturbation - reference
diff_cube = get_diff(var_dict['pert'],var_dict['ref'])
plt.plot(years,diff_cube.data,linestyle=PlotStyle.styles[idx],color=PlotStyle.colors[idx],label=dataset)
if plt_config['write_data']:
# Write var arrays to csv
plt_config['config_alias'] = dataset
save_plot_data(var_short,years,plt_type='diff')
default_plt_name = get_default_plot_name(var_short,plt_type='diff')
else:
# Variable timeseries plot.
for idx,var_obj in enumerate(vars_to_plot):
plt.plot(years,var_obj.cube.data,label=var_obj.alias)
if plt_config['write_data']:
# Write var arrays to csv
plt_config['config_alias'] = var_obj.alias
save_plot_data(var_short,plt_config)
default_plt_name = get_default_plot_name(var_short,plt_config)
plt.xlabel('Year')
plt.ylabel('{} ({})'.format(var_short,units))
plt.title(plt_config['title'].format(var_obj.exp_full,var_long))
plt.tight_layout()
if 'ggplot' in plt_config and not plt_config['ggplot']:
# Only call when not using ggplot style,otherwise no grid lines will be visible.
plt.grid()
plt.legend()
# Adjust figure size
fig = plt.gcf()
fig.set_size_inches(12,8)
plt.close()
但是,当我将函数参数之一更改为 plt_type='diff'
并运行它时,出现此错误:
UnboundLocalError: local variable 'var_obj' referenced before assignment
错误日志指向这行代码:plt.title(plt_config['title'].format(var_obj.exp_full,var_long))
为了纠正这个错误,我尝试在函数中添加 global var_obj
,但是我得到了这个错误:NameError: name 'var_obj' is not defined
我错过了什么?
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)