We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN 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)
```

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `arviz/inference_data.py`
Content:
```
1 """Data structure for using netcdf groups with xarray."""
2 import netCDF4 as nc
3 import xarray as xr
4 
5 
6 class InferenceData():
7     """Container for accessing netCDF files using xarray."""
8 
9     def __init__(self, *_, **kwargs):
10         """Initialize InferenceData object from keyword xarray datasets.
11 
12         Examples
13         --------
14         InferenceData(posterior=posterior, prior=prior)
15 
16         Parameters
17         ----------
18         kwargs :
19             Keyword arguments of xarray datasets
20         """
21         self._groups = []
22         for key, dataset in kwargs.items():
23             if dataset is None:
24                 continue
25             elif not isinstance(dataset, xr.Dataset):
26                 raise ValueError('Arguments to InferenceData must be xarray Datasets '
27                                  '(argument "{}" was type "{}")'.format(key, type(dataset)))
28             setattr(self, key, dataset)
29             self._groups.append(key)
30 
31     def __repr__(self):
32         """Make string representation of object."""
33         return 'Inference data with groups:\n\t> {options}'.format(
34             options='\n\t> '.join(self._groups)
35         )
36 
37     @staticmethod
38     def from_netcdf(filename):
39         """Initialize object from a netcdf file.
40 
41         Expects that the file will have groups, each of which can be loaded by xarray.
42 
43         Parameters
44         ----------
45         filename : str
46             location of netcdf file
47 
48         Returns
49         -------
50         InferenceData object
51         """
52         groups = {}
53         for group in nc.Dataset(filename, mode='r').groups:
54             groups[group] = xr.open_dataset(filename, group=group, autoclose=True)
55         return InferenceData(**groups)
56 
57     def to_netcdf(self, filename):
58         """Write InferenceData to file using netcdf4.
59 
60         Parameters
61         ----------
62         filename : str
63             Location to write to
64 
65         Returns
66         -------
67         str
68             Location of netcdf file
69         """
70         mode = 'w' # overwrite first, then append
71         for group in self._groups:
72             data = getattr(self, group)
73             data.to_netcdf(filename, mode=mode, group=group)
74             data.close()
75             mode = 'a'
76         return filename
77
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

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 @@
         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):

{"golden_diff": "diff --git a/arviz/inference_data.py b/arviz/inference_data.py\n--- a/arviz/inference_data.py\n+++ b/arviz/inference_data.py\n@@ -50,8 +50,12 @@\n         InferenceData object\n         \"\"\"\n         groups = {}\n-        for group in nc.Dataset(filename, mode='r').groups:\n-            groups[group] = xr.open_dataset(filename, group=group, autoclose=True)\n+        with nc.Dataset(filename, mode='r') as data:\n+            data_groups = list(data.groups)\n+\n+        for group in data_groups:\n+            with xr.open_dataset(filename, group=group) as data:\n+                groups[group] = data\n         return InferenceData(**groups)\n \n     def to_netcdf(self, filename):\n", "issue": "Changing the order of plotting and file load seems to cause netcdf errors\nFor 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\r\n\r\n\r\nLoad, Load, Plot, Plot doesn't work. Stack trace attached\r\n[stack_trace.txt](https://github.com/arviz-devs/arviz/files/2349232/stack_trace.txt)\r\n\r\n```\r\nimport arviz as az\r\naz.style.use('arviz-darkgrid')\r\n\r\nnon_centered = az.load_arviz_data('non_centered_eight')\r\ncentered = az.load_arviz_data('centered_eight')\r\naz.violintraceplot(non_centered, var_names=[\"mu\", \"tau\"], textsize=8)\r\naz.violintraceplot(centered, var_names=[\"mu\", \"tau\"], textsize=8)\r\n```\r\n\r\nLoad, Plot, Load, Plot works\r\n\r\n```\r\nimport arviz as az\r\naz.style.use('arviz-darkgrid')\r\n\r\nnon_centered = az.load_arviz_data('non_centered_eight')\r\naz.violintraceplot(non_centered, var_names=[\"mu\", \"tau\"], textsize=8)\r\n\r\ncentered = az.load_arviz_data('centered_eight')\r\naz.violintraceplot(centered, var_names=[\"mu\", \"tau\"], textsize=8)\r\n```\n", "before_files": [{"content": "\"\"\"Data structure for using netcdf groups with xarray.\"\"\"\nimport netCDF4 as nc\nimport xarray as xr\n\n\nclass InferenceData():\n    \"\"\"Container for accessing netCDF files using xarray.\"\"\"\n\n    def __init__(self, *_, **kwargs):\n        \"\"\"Initialize InferenceData object from keyword xarray datasets.\n\n        Examples\n        --------\n        InferenceData(posterior=posterior, prior=prior)\n\n        Parameters\n        ----------\n        kwargs :\n            Keyword arguments of xarray datasets\n        \"\"\"\n        self._groups = []\n        for key, dataset in kwargs.items():\n            if dataset is None:\n                continue\n            elif not isinstance(dataset, xr.Dataset):\n                raise ValueError('Arguments to InferenceData must be xarray Datasets '\n                                 '(argument \"{}\" was type \"{}\")'.format(key, type(dataset)))\n            setattr(self, key, dataset)\n            self._groups.append(key)\n\n    def __repr__(self):\n        \"\"\"Make string representation of object.\"\"\"\n        return 'Inference data with groups:\\n\\t> {options}'.format(\n            options='\\n\\t> '.join(self._groups)\n        )\n\n    @staticmethod\n    def from_netcdf(filename):\n        \"\"\"Initialize object from a netcdf file.\n\n        Expects that the file will have groups, each of which can be loaded by xarray.\n\n        Parameters\n        ----------\n        filename : str\n            location of netcdf file\n\n        Returns\n        -------\n        InferenceData object\n        \"\"\"\n        groups = {}\n        for group in nc.Dataset(filename, mode='r').groups:\n            groups[group] = xr.open_dataset(filename, group=group, autoclose=True)\n        return InferenceData(**groups)\n\n    def to_netcdf(self, filename):\n        \"\"\"Write InferenceData to file using netcdf4.\n\n        Parameters\n        ----------\n        filename : str\n            Location to write to\n\n        Returns\n        -------\n        str\n            Location of netcdf file\n        \"\"\"\n        mode = 'w' # overwrite first, then append\n        for group in self._groups:\n            data = getattr(self, group)\n            data.to_netcdf(filename, mode=mode, group=group)\n            data.close()\n            mode = 'a'\n        return filename\n", "path": "arviz/inference_data.py"}], "after_files": [{"content": "\"\"\"Data structure for using netcdf groups with xarray.\"\"\"\nimport netCDF4 as nc\nimport xarray as xr\n\n\nclass InferenceData():\n    \"\"\"Container for accessing netCDF files using xarray.\"\"\"\n\n    def __init__(self, *_, **kwargs):\n        \"\"\"Initialize InferenceData object from keyword xarray datasets.\n\n        Examples\n        --------\n        InferenceData(posterior=posterior, prior=prior)\n\n        Parameters\n        ----------\n        kwargs :\n            Keyword arguments of xarray datasets\n        \"\"\"\n        self._groups = []\n        for key, dataset in kwargs.items():\n            if dataset is None:\n                continue\n            elif not isinstance(dataset, xr.Dataset):\n                raise ValueError('Arguments to InferenceData must be xarray Datasets '\n                                 '(argument \"{}\" was type \"{}\")'.format(key, type(dataset)))\n            setattr(self, key, dataset)\n            self._groups.append(key)\n\n    def __repr__(self):\n        \"\"\"Make string representation of object.\"\"\"\n        return 'Inference data with groups:\\n\\t> {options}'.format(\n            options='\\n\\t> '.join(self._groups)\n        )\n\n    @staticmethod\n    def from_netcdf(filename):\n        \"\"\"Initialize object from a netcdf file.\n\n        Expects that the file will have groups, each of which can be loaded by xarray.\n\n        Parameters\n        ----------\n        filename : str\n            location of netcdf file\n\n        Returns\n        -------\n        InferenceData object\n        \"\"\"\n        groups = {}\n        with nc.Dataset(filename, mode='r') as data:\n            data_groups = list(data.groups)\n\n        for group in data_groups:\n            with xr.open_dataset(filename, group=group) as data:\n                groups[group] = data\n        return InferenceData(**groups)\n\n    def to_netcdf(self, filename):\n        \"\"\"Write InferenceData to file using netcdf4.\n\n        Parameters\n        ----------\n        filename : str\n            Location to write to\n\n        Returns\n        -------\n        str\n            Location of netcdf file\n        \"\"\"\n        mode = 'w' # overwrite first, then append\n        for group in self._groups:\n            data = getattr(self, group)\n            data.to_netcdf(filename, mode=mode, group=group)\n            data.close()\n            mode = 'a'\n        return filename\n", "path": "arviz/inference_data.py"}]}