Coverage for /home/martinb/.local/share/virtualenvs/camcops/lib/python3.6/site-packages/statsmodels/tsa/vector_ar/plotting.py : 11%

Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1from statsmodels.compat.python import lrange
2import numpy as np
3import statsmodels.tsa.vector_ar.util as util
6class MPLConfigurator(object):
8 def __init__(self):
9 self._inverse_actions = []
11 def revert(self):
12 for action in self._inverse_actions:
13 action()
15 def set_fontsize(self, size):
16 import matplotlib as mpl
17 old_size = mpl.rcParams['font.size']
18 mpl.rcParams['font.size'] = size
20 def revert():
21 mpl.rcParams['font.size'] = old_size
23 self._inverse_actions.append(revert)
26#-------------------------------------------------------------------------------
27# Plotting functions
29def plot_mts(Y, names=None, index=None):
30 """
31 Plot multiple time series
32 """
33 import matplotlib.pyplot as plt
35 k = Y.shape[1]
36 rows, cols = k, 1
38 fig = plt.figure(figsize=(10, 10))
40 for j in range(k):
41 ts = Y[:, j]
43 ax = fig.add_subplot(rows, cols, j+1)
44 if index is not None:
45 ax.plot(index, ts)
46 else:
47 ax.plot(ts)
49 if names is not None:
50 ax.set_title(names[j])
52 return fig
55def plot_var_forc(prior, forc, err_upper, err_lower,
56 index=None, names=None, plot_stderr=True,
57 legend_options=None):
58 import matplotlib.pyplot as plt
60 n, k = prior.shape
61 rows, cols = k, 1
63 fig = plt.figure(figsize=(10, 10))
65 prange = np.arange(n)
66 rng_f = np.arange(n - 1, n + len(forc))
67 rng_err = np.arange(n, n + len(forc))
69 for j in range(k):
70 ax = plt.subplot(rows, cols, j+1)
72 p1 = ax.plot(prange, prior[:, j], 'k', label='Observed')
73 p2 = ax.plot(rng_f, np.r_[prior[-1:, j], forc[:, j]], 'k--',
74 label='Forecast')
76 if plot_stderr:
77 p3 = ax.plot(rng_err, err_upper[:, j], 'k-.',
78 label='Forc 2 STD err')
79 ax.plot(rng_err, err_lower[:, j], 'k-.')
81 if names is not None:
82 ax.set_title(names[j])
84 if legend_options is None:
85 legend_options = {"loc": "upper right"}
86 ax.legend(**legend_options)
87 return fig
90def plot_with_error(y, error, x=None, axes=None, value_fmt='k',
91 error_fmt='k--', alpha=0.05, stderr_type = 'asym'):
92 """
93 Make plot with optional error bars
95 Parameters
96 ----------
97 y :
98 error : array or None
99 """
100 import matplotlib.pyplot as plt
102 if axes is None:
103 axes = plt.gca()
105 x = x if x is not None else lrange(len(y))
106 plot_action = lambda y, fmt: axes.plot(x, y, fmt)
107 plot_action(y, value_fmt)
109 #changed this
110 if error is not None:
111 if stderr_type == 'asym':
112 q = util.norm_signif_level(alpha)
113 plot_action(y - q * error, error_fmt)
114 plot_action(y + q * error, error_fmt)
115 if stderr_type in ('mc','sz1','sz2','sz3'):
116 plot_action(error[0], error_fmt)
117 plot_action(error[1], error_fmt)
120def plot_full_acorr(acorr, fontsize=8, linewidth=8, xlabel=None,
121 err_bound=None):
122 """
124 Parameters
125 ----------
126 """
127 import matplotlib.pyplot as plt
129 config = MPLConfigurator()
130 config.set_fontsize(fontsize)
132 k = acorr.shape[1]
133 fig, axes = plt.subplots(k, k, figsize=(10, 10), squeeze=False)
135 for i in range(k):
136 for j in range(k):
137 ax = axes[i][j]
138 acorr_plot(acorr[:, i, j], linewidth=linewidth,
139 xlabel=xlabel, ax=ax)
141 if err_bound is not None:
142 ax.axhline(err_bound, color='k', linestyle='--')
143 ax.axhline(-err_bound, color='k', linestyle='--')
145 adjust_subplots()
146 config.revert()
148 return fig
151def acorr_plot(acorr, linewidth=8, xlabel=None, ax=None):
152 import matplotlib.pyplot as plt
154 if ax is None:
155 ax = plt.gca()
157 if xlabel is None:
158 xlabel = np.arange(len(acorr))
160 ax.vlines(xlabel, [0], acorr, lw=linewidth)
162 ax.axhline(0, color='k')
163 ax.set_ylim([-1, 1])
165 # hack?
166 ax.set_xlim([-1, xlabel[-1] + 1])
169def plot_acorr_with_error():
170 raise NotImplementedError
173def adjust_subplots(**kwds):
174 import matplotlib.pyplot as plt
176 passed_kwds = dict(bottom=0.05, top=0.925,
177 left=0.05, right=0.95,
178 hspace=0.2)
179 passed_kwds.update(kwds)
180 plt.subplots_adjust(**passed_kwds)
183#-------------------------------------------------------------------------------
184# Multiple impulse response (cum_effects, etc.) cplots
186def irf_grid_plot(values, stderr, impcol, rescol, names, title,
187 signif=0.05, hlines=None, subplot_params=None,
188 plot_params=None, figsize=(10,10), stderr_type='asym'):
189 """
190 Reusable function to make flexible grid plots of impulse responses and
191 comulative effects
193 values : (T + 1) x k x k
194 stderr : T x k x k
195 hlines : k x k
196 """
197 import matplotlib.pyplot as plt
199 if subplot_params is None:
200 subplot_params = {}
201 if plot_params is None:
202 plot_params = {}
204 nrows, ncols, to_plot = _get_irf_plot_config(names, impcol, rescol)
206 fig, axes = plt.subplots(nrows=nrows, ncols=ncols, sharex=True,
207 squeeze=False, figsize=figsize)
209 # fill out space
210 adjust_subplots()
212 fig.suptitle(title, fontsize=14)
214 subtitle_temp = r'%s$\rightarrow$%s'
216 k = len(names)
218 rng = lrange(len(values))
219 for (j, i, ai, aj) in to_plot:
220 ax = axes[ai][aj]
222 # HACK?
223 if stderr is not None:
224 if stderr_type == 'asym':
225 sig = np.sqrt(stderr[:, j * k + i, j * k + i])
226 plot_with_error(values[:, i, j], sig, x=rng, axes=ax,
227 alpha=signif, value_fmt='b', stderr_type=stderr_type)
228 if stderr_type in ('mc','sz1','sz2','sz3'):
229 errs = stderr[0][:, i, j], stderr[1][:, i, j]
230 plot_with_error(values[:, i, j], errs, x=rng, axes=ax,
231 alpha=signif, value_fmt='b', stderr_type=stderr_type)
232 else:
233 plot_with_error(values[:, i, j], None, x=rng, axes=ax,
234 value_fmt='b')
236 ax.axhline(0, color='k')
238 if hlines is not None:
239 ax.axhline(hlines[i,j], color='k')
241 sz = subplot_params.get('fontsize', 12)
242 ax.set_title(subtitle_temp % (names[j], names[i]), fontsize=sz)
244 return fig
247def _get_irf_plot_config(names, impcol, rescol):
248 nrows = ncols = k = len(names)
249 if impcol is not None and rescol is not None:
250 # plot one impulse-response pair
251 nrows = ncols = 1
252 j = util.get_index(names, impcol)
253 i = util.get_index(names, rescol)
254 to_plot = [(j, i, 0, 0)]
255 elif impcol is not None:
256 # plot impacts of impulse in one variable
257 ncols = 1
258 j = util.get_index(names, impcol)
259 to_plot = [(j, i, i, 0) for i in range(k)]
260 elif rescol is not None:
261 # plot only things having impact on particular variable
262 ncols = 1
263 i = util.get_index(names, rescol)
264 to_plot = [(j, i, j, 0) for j in range(k)]
265 else:
266 # plot everything
267 to_plot = [(j, i, i, j) for i in range(k) for j in range(k)]
269 return nrows, ncols, to_plot
271#-------------------------------------------------------------------------------
272# Forecast error variance decomposition