Repository: kutaslab/fitgrid

Issue:
Fitgrid.grid.plot_betas() is unhappy with lots of betas
such as modeling 32 individual subjects with all single trial epochs in the whole experiment in the pd.DataFrame

```
>>> article_fg=(fg_epochs.lm(LHS=model_chans, RHS='data_group + data_group:orth_article_initial_cloze - 1'))
>>> article_fg.plot_betas()
```

```{python}
ValueError                                Traceback (most recent call last)
<ipython-input-242-e56b00933b1f> in <module>()
----> 1 article_fg.plot_betas()

~/.conda/envs/UDCK18/lib/python3.6/site-packages/fitgrid/fitgrid.py in plot_betas(self)
    250                 )
    251 
--> 252             fig.tight_layout()
    253 
    254     def plot_adj_rsquared(self):

~/.conda/envs/UDCK18/lib/python3.6/site-packages/matplotlib/figure.py in tight_layout(self, renderer, pad, h_pad, w_pad, rect)
   2274             self, self.axes, subplotspec_list, renderer,
   2275             pad=pad, h_pad=h_pad, w_pad=w_pad, rect=rect)
-> 2276         self.subplots_adjust(**kwargs)
   2277 
   2278     def align_xlabels(self, axs=None):

~/.conda/envs/UDCK18/lib/python3.6/site-packages/matplotlib/figure.py in subplots_adjust(self, *args, **kwargs)
   2086 
   2087         """
-> 2088         self.subplotpars.update(*args, **kwargs)
   2089         for ax in self.axes:
   2090             if not isinstance(ax, SubplotBase):

~/.conda/envs/UDCK18/lib/python3.6/site-packages/matplotlib/figure.py in update(self, left, bottom, right, top, wspace, hspace)
    239             if self.left >= self.right:
    240                 reset()
--> 241                 raise ValueError('left cannot be >= right')
    242 
    243             if self.bottom >= self.top:

ValueError: left cannot be >= right
```

Discussion:
codecov-io: # [Codecov](https://codecov.io/gh/kutaslab/fitgrid/pull/54?src=pr&el=h1) Report
> Merging [#54](https://codecov.io/gh/kutaslab/fitgrid/pull/54?src=pr&el=desc) into [master](https://codecov.io/gh/kutaslab/fitgrid/commit/02b618f14944e15765bf2066a29dbd77c83c9be7?src=pr&el=desc) will **increase** coverage by `3.43%`.
> The diff coverage is `94.11%`.

[![Impacted file tree graph](https://codecov.io/gh/kutaslab/fitgrid/pull/54/graphs/tree.svg?width=650&token=d9xVBW7gSn&height=150&src=pr)](https://codecov.io/gh/kutaslab/fitgrid/pull/54?src=pr&el=tree)

```diff
@@            Coverage Diff            @@
##           master     #54      +/-   ##
=========================================
+ Coverage   79.46%   82.9%   +3.43%     
=========================================
  Files           8       8              
  Lines         414     503      +89     
=========================================
+ Hits          329     417      +88     
- Misses         85      86       +1
```


| [Impacted Files](https://codecov.io/gh/kutaslab/fitgrid/pull/54?src=pr&el=tree) | Coverage Δ | |
|---|---|---|
| [fitgrid/fitgrid.py](https://codecov.io/gh/kutaslab/fitgrid/pull/54/diff?src=pr&el=tree#diff-Zml0Z3JpZC9maXRncmlkLnB5) | `93.11% <94.11%> (+3.97%)` | :arrow_up: |

------

[Continue to review full report at Codecov](https://codecov.io/gh/kutaslab/fitgrid/pull/54?src=pr&el=continue).
> **Legend** - [Click here to learn more](https://docs.codecov.io/docs/codecov-delta)
> `Δ = absolute <relative> (impact)`, `ø = not affected`, `? = missing data`
> Powered by [Codecov](https://codecov.io/gh/kutaslab/fitgrid/pull/54?src=pr&el=footer). Last update [02b618f...be9be3b](https://codecov.io/gh/kutaslab/fitgrid/pull/54?src=pr&el=lastupdated). Read the [comment docs](https://docs.codecov.io/docs/pull-request-comments).


Patch:
diff --git a/fitgrid/fitgrid.py b/fitgrid/fitgrid.py
index d83530a..4d50b48 100644
--- a/fitgrid/fitgrid.py
+++ b/fitgrid/fitgrid.py
@@ -250,7 +250,7 @@ class FitGrid:
         samples, chans = self._grid.shape
         return f'{samples} by {chans} FitGrid of type {type(self.tester)}.'
 
-    def plot_betas(self):
+    def plot_betas(self, legend_on_bottom=False):
         """Plot betas of the model, one plot per channel, overplotting betas.
         """
 
@@ -264,25 +264,37 @@ class FitGrid:
             channels, betas = params.columns.levels
             figsize = (16, 4 * len(channels))
 
+            n_plots = len(channels) + 1 if legend_on_bottom else len(channels)
+
             fig, axes = plt.subplots(
-                nrows=len(channels), figsize=figsize, sharey=True
+                nrows=n_plots, figsize=figsize, sharey=True
             )
 
-            # wrap in list to allow for zipping later
+            # wrap in list if single axis to allow for zipping later
             if not isinstance(axes, np.ndarray):
                 axes = [axes]
 
+            if legend_on_bottom:
+                legend_ax = axes[-1]
+                axes = axes[:-1]
+
             for ax, chan in zip(axes, channels):
                 for beta in params[chan]:
                     ax.plot(params[chan][beta], label=beta)
                 ax.set(ylabel=chan, xlabel=params.index.name)
-                ax.legend(
-                    loc='upper center',
-                    ncol=len(params[chan]),
-                    bbox_to_anchor=(0.5, 1.2),
-                    fancybox=True,
-                    shadow=False,
-                )
+                if not legend_on_bottom:
+                    ax.legend(
+                        loc='upper center',
+                        ncol=len(params[chan]),
+                        bbox_to_anchor=(0.5, 1.2),
+                        fancybox=True,
+                        shadow=False,
+                    )
+
+            if legend_on_bottom:
+                handles, labels = ax.get_legend_handles_labels()
+                legend_ax.set_axis_off()
+                legend_ax.legend(handles, labels, mode='expand', ncol=3)
 
             fig.tight_layout()
 


Test patch:
diff --git a/tests/test_fitgrid.py b/tests/test_fitgrid.py
index e6b483c..f256a86 100644
--- a/tests/test_fitgrid.py
+++ b/tests/test_fitgrid.py
@@ -171,6 +171,16 @@ def test__smoke_plot_betas():
     grid.plot_betas()
 
 
+def test__smoke_plot_betas_legend_on_bottom():
+
+    epochs = fitgrid.generate()
+    grid = epochs.lm(
+        LHS=['channel0', 'channel1', 'channel2'],
+        RHS='categorical + continuous',
+    )
+    grid.plot_betas(legend_on_bottom=True)
+
+
 # https://github.com/kutaslab/fitgrid/issues/51
 def test__plot_betas_single_channel():