diff --git a/xhistogram/xarray.py b/xhistogram/xarray.py
index 230a44c..c4d41d8 100644
--- a/xhistogram/xarray.py
+++ b/xhistogram/xarray.py
@@ -4,6 +4,7 @@ Xarray API for xhistogram.
 
 import xarray as xr
 import numpy as np
+from collections import OrderedDict
 from .core import histogram as _histogram
 
 
@@ -95,11 +96,11 @@ def histogram(*args, bins=None, dim=None, weights=None, density=False,
 
     # roll our own broadcasting
     # now manually expand the arrays
-    all_dims = set([d for a in args for d in a.dims])
-    all_dims_ordered = list(all_dims)
+    all_dims = [d for a in args for d in a.dims]
+    all_dims_ordered = list(OrderedDict.fromkeys(all_dims))
     args_expanded = []
     for a in args:
-        expand_keys = all_dims - set(a.dims)
+        expand_keys = [d for d in all_dims_ordered if d not in a.dims]
         a_expanded = a.expand_dims({k: 1 for k in expand_keys})
         args_expanded.append(a_expanded)
 
@@ -118,7 +119,7 @@ def histogram(*args, bins=None, dim=None, weights=None, density=False,
         weights_data = None
 
     if dim is not None:
-        dims_to_keep = [d for d in a_dims if d not in dim]
+        dims_to_keep = [d for d in all_dims_ordered if d not in dim]
         axis = [args_transposed[0].get_axis_num(d) for d in dim]
     else:
         dims_to_keep = []
@@ -129,11 +130,19 @@ def histogram(*args, bins=None, dim=None, weights=None, density=False,
 
     # create output dims
     new_dims = [a.name + bin_dim_suffix for a in args[:N_args]]
-    bin_centers = [0.5*(bin[:-1] + bin[1:]) for bin in bins]
-    coords = {name: ((name,), bin_center, a.attrs)
-              for name, bin_center, a in zip(new_dims, bin_centers, args)}
     output_dims = dims_to_keep + new_dims
 
+    # create new coords
+    bin_centers = [0.5*(bin[:-1] + bin[1:]) for bin in bins]
+    new_coords = {name: ((name,), bin_center, a.attrs)
+                  for name, bin_center, a in zip(new_dims, bin_centers, args)}
+
+    old_coords = {name: a0[name]
+                  for name in dims_to_keep if name in a0.coords}
+    all_coords = {}
+    all_coords.update(old_coords)
+    all_coords.update(new_coords)
+
     # CF conventions tell us how to specify cell boundaries
     # http://cfconventions.org/Data/cf-conventions/cf-conventions-1.7/cf-conventions.html#cell-boundaries
     # However, they require introduction of an additional dimension.
@@ -143,7 +152,8 @@ def histogram(*args, bins=None, dim=None, weights=None, density=False,
                   for name, bin_edge, a in zip(edge_dims, bins, args)}
 
     output_name = '_'.join(['histogram'] + [a.name for a in args[:N_args]])
-    da_out = xr.DataArray(h_data, dims=output_dims, coords=coords,
+
+    da_out = xr.DataArray(h_data, dims=output_dims, coords=all_coords,
                           name=output_name)
     return da_out
 

axes not used for making hist got shifted
Say we have two xarray.DataArrays with dims (t:4, z:10, x:100, y:100). If we make histagram based on dimensions x and y, what we have in the result is  (t:10, z:4, x_bin, y_bin).  The t and z get exchanged. 


```python
import numpy as np
import xarray as xr
from xhistogram.xarray import histogram


# create data for testing

time_axis = range(4)
depth_axis = range(10)
X_axis = range(30)
Y_axis = range(30)

dat1 = np.random.randint(low = 0, high = 100,size=(len(time_axis),len(depth_axis),len(X_axis),len(Y_axis)))
array1 = xr.DataArray(dat1, coords = [time_axis,depth_axis,X_axis,Y_axis], dims = ['time','depth','X','Y'])

dat2 = np.random.randint(low = 0, high = 50,size=(len(time_axis),len(depth_axis),len(X_axis),len(Y_axis)))
array2 = xr.DataArray(dat2, coords = [time_axis,depth_axis,X_axis,Y_axis], dims = ['time','depth','X','Y'])

# create bins and rename arrays

bins1 = np.linspace(0, 100, 50)
bins2 = np.linspace(0,50,25)

array1 = array1.rename('one')
array2 = array2.rename('two')

result= histogram(array1,array2,dim = ['X','Y'] , bins=[bins1,bins2])
```

The dimensions of result is (time: 10, depth: 4, one_bin: 49, two_bin: 24) instead of (time: 4, depth: 10, one_bin: 49, two_bin: 24). Is this a bug of the code or just my misusing of the function?
diff --git a/xhistogram/test/test_xarray.py b/xhistogram/test/test_xarray.py
index 9b46dd4..0018f0d 100644
--- a/xhistogram/test/test_xarray.py
+++ b/xhistogram/test/test_xarray.py
@@ -94,3 +94,31 @@ def test_weights(ones, ndims):
                 for d in combinations(dims, nc+1):
                     h = histogram(ones, weights=weights, bins=[bins], dim=d)
                     _check_result(h, d)
+
+
+# test for issue #5
+def test_dims_and_coords():
+    time_axis = np.arange(4)
+    depth_axis = np.arange(10)
+    X_axis = np.arange(30)
+    Y_axis = np.arange(30)
+
+    dat1 = np.random.randint(low=0, high=100,
+                             size=(len(time_axis), len(depth_axis),
+                                   len(X_axis), len(Y_axis)))
+    array1 = xr.DataArray(dat1, coords=[time_axis,depth_axis,X_axis,Y_axis],
+                          dims=['time', 'depth', 'X', 'Y'], name='one')
+
+    dat2 = np.random.randint(low=0, high=50,
+                             size=(len(time_axis), len(depth_axis),
+                                   len(X_axis), len(Y_axis)))
+    array2 = xr.DataArray(dat2, coords=[time_axis,depth_axis,X_axis,Y_axis],
+                          dims=['time','depth','X','Y'], name='two')
+
+    bins1 = np.linspace(0, 100, 50)
+    bins2 = np.linspace(0,50,25)
+
+    result = histogram(array1,array2,dim = ['X','Y'] , bins=[bins1,bins2])
+    assert result.dims == ('time', 'depth', 'one_bin', 'two_bin')
+    assert result.time.identical(array1.time)
+    assert result.depth.identical(array2.depth)

doc/environment.yml
pip install -e .[dev]
parse_log_pytest
environment.yml
pytest
3.6
pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning
alabaster @ file:///home/ktietz/src/ci/alabaster_1611921544520/work
async-generator==1.10
attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work
Babel @ file:///tmp/build/80754af9/babel_1620871417480/work
backcall @ file:///home/ktietz/src/ci/backcall_1611930011877/work
bleach==4.1.0
brotlipy==0.7.0
certifi==2021.5.30
cffi @ file:///tmp/build/80754af9/cffi_1625814693874/work
cftime @ file:///tmp/build/80754af9/cftime_1621828180029/work
charset-normalizer @ file:///tmp/build/80754af9/charset-normalizer_1630003229654/work
colorama @ file:///tmp/build/80754af9/colorama_1607707115595/work
cryptography @ file:///tmp/build/80754af9/cryptography_1635366128178/work
cycler @ file:///tmp/build/80754af9/cycler_1637851556182/work
dask==2021.3.0
decorator @ file:///opt/conda/conda-bld/decorator_1643638310831/work
defusedxml==0.7.1
docutils @ file:///tmp/build/80754af9/docutils_1620827982266/work
entrypoints==0.3
idna @ file:///tmp/build/80754af9/idna_1637925883363/work
imagesize @ file:///tmp/build/80754af9/imagesize_1637939814114/work
importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1631916693255/work
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
ipykernel @ file:///tmp/build/80754af9/ipykernel_1596206602906/work/dist/ipykernel-5.3.4-py3-none-any.whl
ipython @ file:///tmp/build/80754af9/ipython_1593447367857/work
ipython-genutils @ file:///tmp/build/80754af9/ipython_genutils_1606773439826/work
jedi @ file:///tmp/build/80754af9/jedi_1606932572482/work
Jinja2 @ file:///opt/conda/conda-bld/jinja2_1647436528585/work
jsonschema==3.2.0
jupyter-client @ file:///opt/conda/conda-bld/jupyter_client_1643638337975/work
jupyter-core @ file:///tmp/build/80754af9/jupyter_core_1633420100582/work
jupyterlab-pygments==0.1.2
kiwisolver @ file:///tmp/build/80754af9/kiwisolver_1612282412546/work
MarkupSafe @ file:///tmp/build/80754af9/markupsafe_1621528150516/work
matplotlib @ file:///tmp/build/80754af9/matplotlib-suite_1613407855456/work
mistune==0.8.4
more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work
nbclient==0.5.9
nbconvert==6.0.7
nbformat==5.1.3
nbsphinx==0.8.8
nest-asyncio @ file:///tmp/build/80754af9/nest-asyncio_1613680548246/work
netCDF4 @ file:///tmp/build/80754af9/netcdf4_1624382869467/work
numpy @ file:///tmp/build/80754af9/numpy_and_numpy_base_1603483703303/work
numpydoc @ file:///tmp/build/80754af9/numpydoc_1605117425582/work
olefile @ file:///Users/ktietz/demo/mc3/conda-bld/olefile_1629805411829/work
packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work
pandas==1.1.5
pandocfilters==1.5.1
parso==0.7.0
pexpect @ file:///tmp/build/80754af9/pexpect_1605563209008/work
pickleshare @ file:///tmp/build/80754af9/pickleshare_1606932040724/work
Pillow @ file:///tmp/build/80754af9/pillow_1625670622947/work
pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work
prompt-toolkit @ file:///tmp/build/80754af9/prompt-toolkit_1633440160888/work
ptyprocess @ file:///tmp/build/80754af9/ptyprocess_1609355006118/work/dist/ptyprocess-0.7.0-py2.py3-none-any.whl
py @ file:///opt/conda/conda-bld/py_1644396412707/work
pycparser @ file:///tmp/build/80754af9/pycparser_1636541352034/work
Pygments==2.14.0
pyOpenSSL @ file:///opt/conda/conda-bld/pyopenssl_1643788558760/work
pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work
pyrsistent==0.18.0
PySocks @ file:///tmp/build/80754af9/pysocks_1605305763431/work
pytest==6.2.4
python-dateutil @ file:///tmp/build/80754af9/python-dateutil_1626374649649/work
pytz==2021.3
PyYAML==6.0.1
pyzmq @ file:///tmp/build/80754af9/pyzmq_1628268400816/work
requests @ file:///opt/conda/conda-bld/requests_1641824580448/work
six @ file:///tmp/build/80754af9/six_1644875935023/work
snowballstemmer @ file:///tmp/build/80754af9/snowballstemmer_1637937080595/work
Sphinx==5.3.0
sphinx-rtd-theme==2.0.0
sphinxcontrib-applehelp @ file:///home/ktietz/src/ci/sphinxcontrib-applehelp_1611920841464/work
sphinxcontrib-devhelp @ file:///home/ktietz/src/ci/sphinxcontrib-devhelp_1611920923094/work
sphinxcontrib-htmlhelp @ file:///tmp/build/80754af9/sphinxcontrib-htmlhelp_1623945626792/work
sphinxcontrib-jquery==4.1
sphinxcontrib-jsmath @ file:///home/ktietz/src/ci/sphinxcontrib-jsmath_1611920942228/work
sphinxcontrib-qthelp @ file:///home/ktietz/src/ci/sphinxcontrib-qthelp_1611921055322/work
sphinxcontrib-serializinghtml @ file:///tmp/build/80754af9/sphinxcontrib-serializinghtml_1624451540180/work
testpath==0.6.0
toml @ file:///tmp/build/80754af9/toml_1616166611790/work
tornado @ file:///tmp/build/80754af9/tornado_1606942266872/work
traitlets @ file:///tmp/build/80754af9/traitlets_1632746497744/work
typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work
urllib3 @ file:///opt/conda/conda-bld/urllib3_1643638302206/work
wcwidth @ file:///Users/ktietz/demo/mc3/conda-bld/wcwidth_1629357192024/work
webencodings==0.5.1
xarray @ file:///tmp/build/80754af9/xarray_1620712737275/work
-e git+https://github.com/xgcm/xhistogram.git@a636393e1d10d2f8609967869c6ce028d3d9ba41#egg=xhistogram
zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work

name: xhistogram
channels:
  - defaults
  - https://repo.anaconda.com/pkgs/main
  - https://repo.anaconda.com/pkgs/r
  - conda-forge
dependencies:
  - _libgcc_mutex=0.1=main
  - _openmp_mutex=5.1=1_gnu
  - alabaster=0.7.12=pyhd3eb1b0_0
  - attrs=21.4.0=pyhd3eb1b0_0
  - babel=2.9.1=pyhd3eb1b0_0
  - backcall=0.2.0=pyhd3eb1b0_0
  - blas=1.0=openblas
  - brotlipy=0.7.0=py36h27cfd23_1003
  - c-ares=1.19.1=h5eee18b_0
  - ca-certificates=2025.2.25=h06a4308_0
  - certifi=2021.5.30=py36h06a4308_0
  - cffi=1.14.6=py36h400218f_0
  - cftime=1.5.0=py36h6323ea4_0
  - charset-normalizer=2.0.4=pyhd3eb1b0_0
  - colorama=0.4.4=pyhd3eb1b0_0
  - cryptography=35.0.0=py36hd23ed53_0
  - curl=8.2.1=h37d81fd_0
  - cycler=0.11.0=pyhd3eb1b0_0
  - dbus=1.13.18=hb2f20db_0
  - decorator=5.1.1=pyhd3eb1b0_0
  - docutils=0.17.1=py36h06a4308_1
  - entrypoints=0.3=py36_0
  - expat=2.6.4=h6a678d5_0
  - fontconfig=2.14.1=h52c9d5c_1
  - freetype=2.12.1=h4a9f257_0
  - giflib=5.2.2=h5eee18b_0
  - glib=2.69.1=h4ff587b_1
  - gst-plugins-base=1.14.1=h6a678d5_1
  - gstreamer=1.14.1=h5eee18b_1
  - hdf4=4.2.13=h3ca952b_2
  - hdf5=1.10.6=h3ffc7dd_1
  - icu=58.2=he6710b0_3
  - idna=3.3=pyhd3eb1b0_0
  - imagesize=1.3.0=pyhd3eb1b0_0
  - importlib-metadata=4.8.1=py36h06a4308_0
  - importlib_metadata=4.8.1=hd3eb1b0_0
  - iniconfig=1.1.1=pyhd3eb1b0_0
  - ipykernel=5.3.4=py36h5ca1d4c_0
  - ipython=7.16.1=py36h5ca1d4c_0
  - ipython_genutils=0.2.0=pyhd3eb1b0_1
  - jedi=0.17.2=py36h06a4308_1
  - jinja2=3.0.3=pyhd3eb1b0_0
  - jpeg=9e=h5eee18b_3
  - jupyter_client=7.1.2=pyhd3eb1b0_0
  - jupyter_core=4.8.1=py36h06a4308_0
  - kiwisolver=1.3.1=py36h2531618_0
  - krb5=1.20.1=h568e23c_1
  - lcms2=2.16=hb9589c4_0
  - ld_impl_linux-64=2.40=h12ee557_0
  - lerc=4.0.0=h6a678d5_0
  - libcurl=8.2.1=h91b91d3_0
  - libdeflate=1.22=h5eee18b_0
  - libedit=3.1.20230828=h5eee18b_0
  - libev=4.33=h7f8727e_1
  - libffi=3.3=he6710b0_2
  - libgcc-ng=11.2.0=h1234567_1
  - libgfortran-ng=11.2.0=h00389a5_1
  - libgfortran5=11.2.0=h1234567_1
  - libgomp=11.2.0=h1234567_1
  - libnetcdf=4.6.1=h2053bdc_4
  - libnghttp2=1.52.0=ha637b67_1
  - libopenblas=0.3.21=h043d6bf_0
  - libpng=1.6.39=h5eee18b_0
  - libsodium=1.0.18=h7b6447c_0
  - libssh2=1.10.0=h37d81fd_2
  - libstdcxx-ng=11.2.0=h1234567_1
  - libtiff=4.5.1=hffd6297_1
  - libuuid=1.41.5=h5eee18b_0
  - libwebp=1.2.4=h11a3e52_1
  - libwebp-base=1.2.4=h5eee18b_1
  - libxcb=1.15=h7f8727e_0
  - libxml2=2.9.14=h74e7548_0
  - lz4-c=1.9.4=h6a678d5_1
  - markupsafe=2.0.1=py36h27cfd23_0
  - matplotlib=3.3.4=py36h06a4308_0
  - matplotlib-base=3.3.4=py36h62a2d02_0
  - more-itertools=8.12.0=pyhd3eb1b0_0
  - ncurses=6.4=h6a678d5_0
  - nest-asyncio=1.5.1=pyhd3eb1b0_0
  - netcdf4=1.5.7=py36h0a24e14_0
  - numpy=1.19.2=py36h6163131_0
  - numpy-base=1.19.2=py36h75fe3a5_0
  - numpydoc=1.1.0=pyhd3eb1b0_1
  - olefile=0.46=pyhd3eb1b0_0
  - openssl=1.1.1w=h7f8727e_0
  - packaging=21.3=pyhd3eb1b0_0
  - pandas=1.1.5=py36ha9443f7_0
  - pandoc=2.12=h06a4308_3
  - parso=0.7.0=py_0
  - pcre=8.45=h295c915_0
  - pexpect=4.8.0=pyhd3eb1b0_3
  - pickleshare=0.7.5=pyhd3eb1b0_1003
  - pillow=8.3.1=py36h5aabda8_0
  - pip=21.2.2=py36h06a4308_0
  - pluggy=0.13.1=py36h06a4308_0
  - prompt-toolkit=3.0.20=pyhd3eb1b0_0
  - ptyprocess=0.7.0=pyhd3eb1b0_2
  - py=1.11.0=pyhd3eb1b0_0
  - pycparser=2.21=pyhd3eb1b0_0
  - pyopenssl=22.0.0=pyhd3eb1b0_0
  - pyparsing=3.0.4=pyhd3eb1b0_0
  - pyqt=5.9.2=py36h05f1152_2
  - pysocks=1.7.1=py36h06a4308_0
  - pytest=6.2.4=py36h06a4308_2
  - python=3.6.13=h12debd9_1
  - python-dateutil=2.8.2=pyhd3eb1b0_0
  - pytz=2021.3=pyhd3eb1b0_0
  - pyzmq=22.2.1=py36h295c915_1
  - qt=5.9.7=h5867ecd_1
  - readline=8.2=h5eee18b_0
  - requests=2.27.1=pyhd3eb1b0_0
  - setuptools=58.0.4=py36h06a4308_0
  - sip=4.19.8=py36hf484d3e_0
  - six=1.16.0=pyhd3eb1b0_1
  - snowballstemmer=2.2.0=pyhd3eb1b0_0
  - sphinxcontrib-applehelp=1.0.2=pyhd3eb1b0_0
  - sphinxcontrib-devhelp=1.0.2=pyhd3eb1b0_0
  - sphinxcontrib-htmlhelp=2.0.0=pyhd3eb1b0_0
  - sphinxcontrib-jsmath=1.0.1=pyhd3eb1b0_0
  - sphinxcontrib-qthelp=1.0.3=pyhd3eb1b0_0
  - sphinxcontrib-serializinghtml=1.1.5=pyhd3eb1b0_0
  - sqlite=3.45.3=h5eee18b_0
  - tk=8.6.14=h39e8969_0
  - toml=0.10.2=pyhd3eb1b0_0
  - tornado=6.1=py36h27cfd23_0
  - traitlets=4.3.3=py36h06a4308_0
  - typing_extensions=4.1.1=pyh06a4308_0
  - urllib3=1.26.8=pyhd3eb1b0_0
  - wcwidth=0.2.5=pyhd3eb1b0_0
  - wheel=0.37.1=pyhd3eb1b0_0
  - xarray=0.18.0=pyhd3eb1b0_0
  - xz=5.6.4=h5eee18b_1
  - zeromq=4.3.5=h6a678d5_0
  - zipp=3.6.0=pyhd3eb1b0_0
  - zlib=1.2.13=h5eee18b_1
  - zstd=1.5.6=hc292b87_0
  - pip:
      - async-generator==1.10
      - bleach==4.1.0
      - dask==2021.3.0
      - defusedxml==0.7.1
      - jsonschema==3.2.0
      - jupyterlab-pygments==0.1.2
      - mistune==0.8.4
      - nbclient==0.5.9
      - nbconvert==6.0.7
      - nbformat==5.1.3
      - nbsphinx==0.8.8
      - pandocfilters==1.5.1
      - pygments==2.14.0
      - pyrsistent==0.18.0
      - pyyaml==6.0.1
      - sphinx==5.3.0
      - sphinx-rtd-theme==2.0.0
      - sphinxcontrib-jquery==4.1
      - testpath==0.6.0
      - webencodings==0.5.1
prefix: /opt/conda/envs/xhistogram

xhistogram/test/test_xarray.py::test_dims_and_coords
xhistogram/test/test_xarray.py::test_histogram_ones[1D-1] xhistogram/test/test_xarray.py::test_histogram_ones[2D-1] xhistogram/test/test_xarray.py::test_histogram_ones[2D-2] xhistogram/test/test_xarray.py::test_histogram_ones[3D-1] xhistogram/test/test_xarray.py::test_histogram_ones[3D-2] xhistogram/test/test_xarray.py::test_histogram_ones[3D-3] xhistogram/test/test_xarray.py::test_histogram_ones[4D-1] xhistogram/test/test_xarray.py::test_histogram_ones[4D-2] xhistogram/test/test_xarray.py::test_histogram_ones[4D-3] xhistogram/test/test_xarray.py::test_histogram_ones[4D-4] xhistogram/test/test_xarray.py::test_weights[1D-1] xhistogram/test/test_xarray.py::test_weights[2D-1] xhistogram/test/test_xarray.py::test_weights[2D-2] xhistogram/test/test_xarray.py::test_weights[3D-1] xhistogram/test/test_xarray.py::test_weights[3D-2] xhistogram/test/test_xarray.py::test_weights[3D-3] xhistogram/test/test_xarray.py::test_weights[4D-1] xhistogram/test/test_xarray.py::test_weights[4D-2] xhistogram/test/test_xarray.py::test_weights[4D-3] xhistogram/test/test_xarray.py::test_weights[4D-4]
xhistogram/xarray.py
xhistogram/xarray.py