internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: arviz-devs/arviz

Issue:
Changing the order of plotting and file load seems to cause netcdf errors
For some reason it seems that changing the order of plotting and loading data causes failures, not entirely sure why yet. This is only occurring for me on Ubuntu 16.04 with the latest version of arviz. It does not occur on my osx laptop


Load, Load, Plot, Plot doesn't work. Stack trace attached
[stack_trace.txt](https://github.com/arviz-devs/arviz/files/2349232/stack_trace.txt)

```
import arviz as az
az.style.use('arviz-darkgrid')

non_centered = az.load_arviz_data('non_centered_eight')
centered = az.load_arviz_data('centered_eight')
az.violintraceplot(non_centered, var_names=["mu", "tau"], textsize=8)
az.violintraceplot(centered, var_names=["mu", "tau"], textsize=8)
```

Load, Plot, Load, Plot works

```
import arviz as az
az.style.use('arviz-darkgrid')

non_centered = az.load_arviz_data('non_centered_eight')
az.violintraceplot(non_centered, var_names=["mu", "tau"], textsize=8)

centered = az.load_arviz_data('centered_eight')
az.violintraceplot(centered, var_names=["mu", "tau"], textsize=8)
```


Discussion:
I've been debugging using this command

> strace -e trace=open,close,read,write,connect, -o violinplot.txt  python violinplot.py

By searching for strings like */home/testuser/repos/arviz/arviz/data/non_centered_eight.nc"* its easier to see where the program is at before failures start happening

Sample log attached
[violinplot.txt](https://github.com/arviz-devs/arviz/files/2349131/violinplot.txt)

Any suggestions @shoyer (we can also open a similar issue there if that is helpful)?

For a little context, `az.load_arviz_data` is calling 

```
xarray.open_dataset(filename=filename, group=group, autoclose=True)
```

There is also an iterator that ends up throwing the exception [here](https://github.com/arviz-devs/arviz/blob/master/arviz/plots/plot_utils.py#L162), which "flattens" an xarray dataset over dimensions and variables.
Please file an xarray bug if you can reduce this to a minimal reproducible example.

The only thing in xarray that should change if you alter the order of variables in a netCDF file is the order over which it is iterated.

Resolving patch:
diff --git a/arviz/inference_data.py b/arviz/inference_data.py
--- a/arviz/inference_data.py
+++ b/arviz/inference_data.py
@@ -50,8 +50,12 @@ def from_netcdf(filename):
         InferenceData object
         """
         groups = {}
-        for group in nc.Dataset(filename, mode='r').groups:
-            groups[group] = xr.open_dataset(filename, group=group, autoclose=True)
+        with nc.Dataset(filename, mode='r') as data:
+            data_groups = list(data.groups)
+
+        for group in data_groups:
+            with xr.open_dataset(filename, group=group) as data:
+                groups[group] = data
         return InferenceData(**groups)
 
     def to_netcdf(self, filename):


Test patch:
Repository: arviz-devs/arviz

Issue:
Store ArviZ logo somewhere
This snippet will save three copies of the logo. We should probably put it somewhere.

```python
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.transforms import Bbox
from matplotlib.path import Path
from matplotlib.patches import PathPatch
from scipy import stats

x = np.linspace(0, 1, 200)
pdfx = stats.beta(2, 5).pdf(x)

path = Path(np.array([x, pdfx]).transpose())
patch = PathPatch(path, facecolor='none', alpha=0)
plt.gca().add_patch(patch)

cmap = matplotlib.colors.LinearSegmentedColormap.from_list('', ["#00bfbf", "#00bfbf", "#126a8a"])

im = plt.imshow(np.array([[1, 0, 0], [1, 1, 0]]),
                cmap=cmap, interpolation='bicubic',
                origin='lower',extent=[0,1, 0.0, 5],
                aspect="auto", clip_path=patch, clip_on=True)

plt.axis('off')
plt.ylim(0, 5.5)
plt.xlim(0, 0.9)

bbox = Bbox([[0.75, 0.5], [5.4, 2.2]])

plt.savefig('logo_00.png', dpi=300,  bbox_inches=bbox, transparent=True)
plt.text(x=0.04, y=-0.01, s='ArviZ', fontdict={'name':'ubuntu mono', 'fontsize':62}, color='w')

plt.savefig('logo_01.png', dpi=300,  bbox_inches=bbox)
plt.savefig('logo_02.png', dpi=300,  bbox_inches=bbox, transparent=True)
```


Discussion:
Should we have also example how to save it with `.svg`? Or is it just 

    plt.savefig('logo_02.svg', dpi=300,  bbox_inches=bbox, transparent=True)
yes, just specify the extension. A logo folder inside doc? or just at the root? 
I vote logo directory in docs like pymc3 does

Resolving patch:
diff --git a/doc/logo/generate_logo.py b/doc/logo/generate_logo.py
new file mode 100644
--- /dev/null
+++ b/doc/logo/generate_logo.py
@@ -0,0 +1,36 @@
+import numpy as np
+import matplotlib
+import matplotlib.pyplot as plt
+from matplotlib.transforms import Bbox
+from matplotlib.path import Path
+from matplotlib.patches import PathPatch
+from scipy import stats
+
+x = np.linspace(0, 1, 200)
+pdfx = stats.beta(2, 5).pdf(x)
+
+path = Path(np.array([x, pdfx]).transpose())
+patch = PathPatch(path, facecolor='none', alpha=0)
+plt.gca().add_patch(patch)
+
+cmap = matplotlib.colors.LinearSegmentedColormap.from_list('', ["#00bfbf", "#00bfbf", "#126a8a"])
+
+im = plt.imshow(np.array([[1, 0, 0], [1, 1, 0]]),
+                cmap=cmap, interpolation='bicubic',
+                origin='lower', extent=[0, 1, 0.0, 5],
+                aspect="auto", clip_path=patch, clip_on=True)
+
+plt.axis('off')
+plt.ylim(0, 5.5)
+plt.xlim(0, 0.9)
+
+bbox = Bbox([[0.75, 0.5], [5.4, 2.2]])
+
+#plt.savefig('logo_00.png', dpi=300,  bbox_inches=bbox, transparent=True)
+plt.text(x=0.04, y=-0.01, s='ArviZ',
+         fontdict={'name': 'ubuntu mono', 'fontsize': 62}, color='w')
+
+plt.savefig('ArviZ.png', dpi=300, bbox_inches=bbox, transparent=True)
+plt.savefig('ArviZ.pdf', dpi=300, bbox_inches=bbox, transparent=True)
+plt.savefig('ArviZ.svg', dpi=300, bbox_inches=bbox, transparent=True)
+plt.savefig('ArviZ.jpg', dpi=300, bbox_inches=bbox, transparent=True)


Test patch:
Repository: arviz-devs/arviz

Issue:
Docs are broken
Looks like one of the examples still uses `n_eff`. From travis: 

```
Exception occurred:
  File "/home/travis/build/arviz-devs/arviz/examples/plot_forest_ridge.py", line 20, in <module>
    n_eff=False)
TypeError: plot_forest() got an unexpected keyword argument 'n_eff'
```


Discussion:
This is fault! I will fix this!

Resolving patch:
diff --git a/examples/plot_forest_ridge.py b/examples/plot_forest_ridge.py
--- a/examples/plot_forest_ridge.py
+++ b/examples/plot_forest_ridge.py
@@ -15,7 +15,5 @@
                            combined=True,
                            textsize=11,
                            ridgeplot_overlap=3,
-                           colors='white',
-                           r_hat=False,
-                           n_eff=False)
+                           colors='white')
 axes[0].set_title('Estimated theta for eight schools model', fontsize=11)


Test patch:
Repository: arviz-devs/arviz

Issue:
Add API docs for plot_ppc
https://arviz-devs.github.io/arviz/generated/arviz.plot_ppc.html#arviz.plot_ppc

See Posterior Docs for example
https://arviz-devs.github.io/arviz/generated/arviz.plot_posterior.html#arviz.plot_posterior


Discussion:
I was just thinking the other day how much Python needed a library like this and then I found arviz. This looks great, thanks for creating this!

I was hoping to help contribute and figured I'd start with one of these. Ok if I take this one up?
Yes, you can take it.
Hey @mattboggess If it helps I wrote some more detailed instructions for someone else here. Thanks for taking the time to contribute!

https://github.com/arviz-devs/arviz/issues/351

Resolving patch:
diff --git a/arviz/plots/ppcplot.py b/arviz/plots/ppcplot.py
--- a/arviz/plots/ppcplot.py
+++ b/arviz/plots/ppcplot.py
@@ -37,6 +37,25 @@ def plot_ppc(
     Returns
     -------
     axes : matplotlib axes
+
+    Examples
+    --------
+    Plot the observed data KDE overlaid on posterior predictive KDEs.
+
+    .. plot::
+        :context: close-figs
+
+        >>> import arviz as az
+        >>> data = az.load_arviz_data('radon')
+        >>> az.plot_ppc(data)
+
+    Plot the overlay with empirical CDFs.
+
+    .. plot::
+        :context: close-figs
+
+        >>> az.plot_ppc(data, kind='cumulative')
+
     """
     for group in ("posterior_predictive", "observed_data"):
         if not hasattr(data, group):


Test patch:
Repository: arviz-devs/arviz

Issue:
Incompatibility with emcee3 pre-release
Trying to use the `from_emcee()` function raises the following error for `emcee3`:

> AttributeError: 'EnsembleSampler' object has no attribute 'args'

This is due to line 29 in `io_emcee.py`:

    num_args = len(sampler.args)

In version 2, the EnsembleSampler class stored this information, but only to pass this to `_function_wrapper` class, which also stored the same information. This wrapper was for the posterior probability, so, `sampler.args` is equivalent to `sampler.lnprobfn.args`.

In version 3, this has been slightly modified, and now only the `_FunctionWrapper` class stores this information, however, its name has also been modified, so in this case it should be retrieved with `sampler.log_prob_fn.args`. 


Discussion:
Are there any other changes? Is `hasattr` enough to extract correct information?
I modified 2 lines of the `io_emcee.py` and now it seems to work also with `emcee` version 3. I changed line 30 to:

    num_args = len(sampler.args) if hasattr(sampler,'args') else len(sampler.log_prob_fn.args)

and line 78 to:

    data[var_name] = self.sampler.args[idx] if hasattr(self.sampler,'args') else self.sampler.log_prob_fn.args[idx]

I don' know if this would be the preferred way, or a `try` statement.

Resolving patch:
diff --git a/arviz/data/io_emcee.py b/arviz/data/io_emcee.py
--- a/arviz/data/io_emcee.py
+++ b/arviz/data/io_emcee.py
@@ -27,7 +27,8 @@ def _verify_names(sampler, var_names, arg_names):
         Defaults for var_names and arg_names
     """
     num_vars = sampler.chain.shape[-1]
-    num_args = len(sampler.args)
+    # Get emcee version 2 sampler args, else get emcee version 3
+    num_args = len(sampler.args) if hasattr(sampler, "args") else len(sampler.log_prob_fn.args)
 
     if var_names is None:
         var_names = ["var_{}".format(idx) for idx in range(num_vars)]
@@ -75,7 +76,12 @@ def observed_data_to_xarray(self):
         """Convert observed data to xarray."""
         data = {}
         for idx, var_name in enumerate(self.arg_names):
-            data[var_name] = self.sampler.args[idx]
+            # Get emcee version 2 sampler args, else get emcee version 3
+            data[var_name] = (
+                self.sampler.args[idx]
+                if hasattr(self.sampler, "args")
+                else self.sampler.log_prob_fn.args[idx]
+            )
         return dict_to_dataset(data, library=self.emcee, coords=self.coords, dims=self.dims)
 
     def to_inference_data(self):


Test patch:
Repository: arviz-devs/arviz

Issue:
Installing arviz breaks pymc3 installation
**Describe the bug**
Installing Arviz breaks a pymc3 installation, which is unfortunate because they're built to be compatible. After installation, importing pymc3 throws the following error. 

> WARNING (theano.tensor.blas): Using NumPy C-API based implementation for BLAS functions.

The reason is because arviz installation requires numpy==1.15 rather than numpy>=1.15. If you have 1.16, it uninstalls it and re-installs 1.15. It's annoying to fix. I ended up having to scrap the whole virtual environment and start over.

**To Reproduce**
Install arviz if you have any version of numpy other than 1.15, then import pymc3. 

**Expected behavior**
Do not force downgrade of numpy. 


Discussion:
Thanks for the report! I can confirm that in the pypi released version, the requirements are:

```
matplotlib>=3.0
numpy==1.15
scipy
pandas
xarray
netcdf4
```
(this fixed a bug that used to exist in numpy)

The best solution would be cutting a release with only that removed, but the easiest solution would be cutting a new release off master asap.
So does this mean that arviz will not work with either older or newer versions of numpy? That's good to know, because my workaround was just to install it either first, or without dependencies and then install the rest of the dependencies individually. But it may mean that if you plan to use arviz you should fix your numpy back to 1.15 in your docker/virtualenv/etc/. 
Might at least be worth a note in the documentation section on using arviz with pymc3 traces. 
@lwahedi Apologies on this issue. It's definitely annoying

To answer your question, It will work with newer versions of numpy, this was a short term fix that we applied due to a numpy bug a couple months ago that was not supposed to make it into production.

We're going to cut a pypi release on Saturday to unpin numpy version (and introduce more features!)

For now the best option would be to install from github master.

Sorry for all the trouble, and we really appreciate you creating this issue

Resolving patch:
diff --git a/arviz/__init__.py b/arviz/__init__.py
--- a/arviz/__init__.py
+++ b/arviz/__init__.py
@@ -1,6 +1,6 @@
 # pylint: disable=wildcard-import,invalid-name,wrong-import-position
 """ArviZ is a library for exploratory analysis of Bayesian models."""
-__version__ = "0.3.2"
+__version__ = "0.3.3"
 
 import os
 import logging


Test patch:
Repository: arviz-devs/arviz

Issue:
Return value of plot_pair is numvars the same
The return value of `plot_pair` is a list that contains `numvars` times the array of subplots. I guess it comes from the original version with gridspec. 

Line 168 defines `axs` empty list, which is no longer used, line 219 appends `ax` to `axs`, but `ax` already contains all the subplots. Eventually, `axs` is returned instead of `ax`.

In addition, maybe the docstring should be updated to specify that `ax` (both as input and as return value) is actually an array of axes, not an axes object. It cannot be a single axes because there are many, but I am not sure if everyone will see it right away.



Discussion:

Resolving patch:
diff --git a/arviz/plots/pairplot.py b/arviz/plots/pairplot.py
--- a/arviz/plots/pairplot.py
+++ b/arviz/plots/pairplot.py
@@ -192,7 +192,6 @@ def plot_pair(
         ax.set_xlabel("{}".format(flat_var_names[0]), fontsize=ax_labelsize, wrap=True)
         ax.set_ylabel("{}".format(flat_var_names[1]), fontsize=ax_labelsize, wrap=True)
         ax.tick_params(labelsize=xt_labelsize)
-        axs = ax
 
     else:
         (figsize, ax_labelsize, _, xt_labelsize, _, _) = _scale_fig_size(
@@ -203,7 +202,6 @@ def plot_pair(
             fig, ax = plt.subplots(
                 numvars - 1, numvars - 1, figsize=figsize, constrained_layout=True
             )
-        axs = []
         hexbin_values = []
         for i in range(0, numvars - 1):
             var1 = _posterior[i]
@@ -254,6 +252,5 @@ def plot_pair(
                     )
 
                 ax[j, i].tick_params(labelsize=xt_labelsize)
-                axs.append(ax)
 
-    return axs
+    return ax


Test patch:
diff --git a/arviz/tests/test_plots.py b/arviz/tests/test_plots.py
--- a/arviz/tests/test_plots.py
+++ b/arviz/tests/test_plots.py
@@ -365,7 +365,7 @@ def test_plot_khat():
 def test_plot_pair(models, model_fit, kwargs):
     obj = getattr(models, model_fit)
     ax = plot_pair(obj, **kwargs)
-    assert ax
+    assert np.all(ax)
 
 
 @pytest.mark.parametrize(
Repository: arviz-devs/arviz

Issue:
densityplot warning tight_layout
plot density returns the following warning:

_UserWarning: This figure was using constrained_layout==True, but that is incompatible with subplots_adjust and or tight_layout: setting constrained_layout==False. 
  warnings.warn("This figure was using constrained_layout==True, ")_

The solution is to do not use tight_layout()





Discussion:

Resolving patch:
diff --git a/arviz/plots/densityplot.py b/arviz/plots/densityplot.py
--- a/arviz/plots/densityplot.py
+++ b/arviz/plots/densityplot.py
@@ -181,7 +181,7 @@ def plot_density(
         figsize, textsize, rows, cols
     )
 
-    fig, ax = _create_axes_grid(length_plotters, rows, cols, figsize=figsize, squeeze=False)
+    _, ax = _create_axes_grid(length_plotters, rows, cols, figsize=figsize, squeeze=False)
 
     axis_map = {label: ax_ for label, ax_ in zip(all_labels, ax.flatten())}
     for m_idx, plotters in enumerate(to_plot):
@@ -209,8 +209,6 @@ def plot_density(
             ax[0].plot([], label=label, c=colors[m_idx], markersize=markersize)
         ax[0].legend(fontsize=xt_labelsize)
 
-    fig.tight_layout()
-
     return ax
 
 


Test patch:
Repository: arviz-devs/arviz

Issue:
Arviz Docs Navbar has site dropdown with duplicate links
#### Summary:
Arviz Docs Navbar has site dropdown with duplicate links. Would be nice to delete the link

#### Description:
https://github.com/ryan-roemer/sphinx-bootstrap-theme/blob/master/sphinx_bootstrap_theme/bootstrap/navbar.html#L21

<img width="939" alt="screen shot 2018-11-15 at 12 16 28 pm" src="https://user-images.githubusercontent.com/7213793/48579124-76df7e00-e8d0-11e8-980f-fbf6a2cb1c65.png">


#### Expected Output:
No site drop down





Discussion:

Resolving patch:
diff --git a/arviz/plots/forestplot.py b/arviz/plots/forestplot.py
--- a/arviz/plots/forestplot.py
+++ b/arviz/plots/forestplot.py
@@ -96,11 +96,14 @@ def plot_forest(
     Returns
     -------
     gridspec : matplotlib GridSpec
+
     Examples
     --------
     Forestpĺot
+
     .. plot::
         :context: close-figs
+
         >>> import arviz as az
         >>> non_centered_data = az.load_arviz_data('non_centered_eight')
         >>> fig, axes = az.plot_forest(non_centered_data,
@@ -110,9 +113,12 @@ def plot_forest(
         >>>                            ridgeplot_overlap=3,
         >>>                            figsize=(9, 7))
         >>> axes[0].set_title('Estimated theta for 8 schools model')
+
     Ridgeplot
+
     .. plot::
         :context: close-figs
+
         >>> fig, axes = az.plot_forest(non_centered_data,
         >>>                            kind='ridgeplot',
         >>>                            var_names=['theta'],


Test patch:
Repository: arviz-devs/arviz

Issue:
add api docs for plot_energy
https://arviz-devs.github.io/arviz/generated/arviz.plot_energy.html#arviz.plot_energy

See Posterior Docs for example
https://arviz-devs.github.io/arviz/generated/arviz.plot_posterior.html#arviz.plot_posterior


Discussion:
@canyon289  Sorry, I want to pick this but not sure what to do. The link you shared has already explained the function. Can you explain what is to be done?
Same instructions as here https://github.com/arviz-devs/arviz/issues/351#issuecomment-428910514

Resolving patch:
diff --git a/arviz/plots/energyplot.py b/arviz/plots/energyplot.py
--- a/arviz/plots/energyplot.py
+++ b/arviz/plots/energyplot.py
@@ -61,6 +61,25 @@ def plot_energy(
     Returns
     -------
     ax : matplotlib axes
+
+    Examples
+    --------
+    Plot a default energy plot
+
+    .. plot::
+        :context: close-figs
+
+        >>> import arviz as az
+        >>> data = az.load_arviz_data('centered_eight')
+        >>> az.plot_energy(data)
+
+    Represent energy plot via histograms
+
+    .. plot::
+        :context: close-figs
+
+        >>> az.plot_energy(data, kind='hist')
+
     """
     energy = convert_to_dataset(data, group="sample_stats").energy.values
 


Test patch:
Repository: arviz-devs/arviz

Issue:
Color scheme not displayed in plot_energy.
The color scheme is not displayed in the legend for a default energy plot.
![arviz-plot_energy-1](https://user-images.githubusercontent.com/29407246/56133923-223d4d80-5fab-11e9-99e3-0e60637d234c.png)

This behavior is not observed when we set `kind='hist'`.
![arviz-plot_energy-2](https://user-images.githubusercontent.com/29407246/56133688-a9d68c80-5faa-11e9-9195-ab7aa2c743a4.png)



Discussion:
Good catch! I checked the code a little, and this is a problem of `plot_kde`. The label is set in `ax.plot`, therefore, when `alpha=0` (or `linewidth`=0) in `plot_kwargs` the legend is empty. Here is another example:

    >>> az.plot_kde(np.random.normal(size=1000), label="Gaussian", plot_kwargs={"alpha":0}, fill_kwargs={"alpha":.7}) 
    # equivalent to
    # az.plot_kde(np.random.normal(size=1000), label="Gaussian", plot_kwargs={"linewidth":0}, fill_kwargs={"alpha":.7})

Outputs:

![plot_kde_wrong_legend](https://user-images.githubusercontent.com/23738400/56252066-708b4300-60b6-11e9-936a-dc2dd2a0a5b3.png)

This can be solved creating the legend from handles. The only thong that will be a little tricky will be passing the arguments in `plot_kwargs` and `fill_kwargs` to the matplotlib `Patch`. I have plenty of experience with this kind of legends, I can try to solve it or help anyone who volunteers. It can also be useful to avoid the ghost plots in `plot_energy` when `bfmi=True`.

In this case, I'll start working on the issue and you can help me in the process.
Great! Feel free to ask anything via gitter. I will also send you some reference that may be useful. I have one starting comment though, which is interesting for everyone too. The docs say _use fill_kwargs={‘alpha’: 0} to disable fill_. And the same approach is used in `plot_energy` to disable the line plot. However, I think it may be a better idea to use `linewidth=0` to disable line plots, which will also make it easier when generating the custom legend handles.
Amazing. I'll start work on this soon.

Resolving patch:
diff --git a/arviz/plots/kdeplot.py b/arviz/plots/kdeplot.py
--- a/arviz/plots/kdeplot.py
+++ b/arviz/plots/kdeplot.py
@@ -2,6 +2,7 @@
 import warnings
 import numpy as np
 import matplotlib.pyplot as plt
+from matplotlib.patches import Patch
 from scipy.signal import gaussian, convolve, convolve2d  # pylint: disable=no-name-in-module
 from scipy.sparse import coo_matrix
 import xarray as xr
@@ -167,6 +168,7 @@ def plot_kde(
         plot_kwargs.setdefault("color", "C0")
 
         default_color = plot_kwargs.get("color")
+
         if fill_kwargs is None:
             fill_kwargs = {}
 
@@ -227,7 +229,8 @@ def plot_kde(
             fill_func(fill_x, fill_y, **fill_kwargs)
 
         if legend and label:
-            ax.legend()
+            legend_element = [Patch(edgecolor=default_color, label=label)]
+            ax.legend(handles=legend_element)
     else:
         if contour_kwargs is None:
             contour_kwargs = {}


Test patch: