I am running Python v3.8.6. When I run the following code, it works.
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, diff_cube.data, plt_config, plt_type='diff')
default_plt_name = get_default_plot_name(var_short, plt_config, plt_type='diff')
else:
# Variable timeseries plot.
for idx, var_obj in enumerate(vars_to_plot):
plt.plot(years, var_obj.cube.data, linestyle=PlotStyle.styles[idx],
color=PlotStyle.colors[idx], 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, years, var_obj.cube.data, 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()
However, when I change one of the function parameters to plt_type='diff' and run it, I get this error:
UnboundLocalError: local variable 'var_obj' referenced before assignment
The error log points to this line of the code: plt.title(plt_config['title'].format(var_obj.exp_full, var_long))
To remedy this error, I tried adding global var_obj within the function, but then I get this error: NameError: name 'var_obj' is not defined
What am I missing?