Skip to content

Additional axis kwargs #2294

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 11 commits into from
Jul 31, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 5 additions & 4 deletions doc/plotting.rst
Original file line number Diff line number Diff line change
Expand Up @@ -212,8 +212,6 @@ If required, the automatic legend can be turned off using ``add_legend=False``.
``hue`` can be passed directly to :py:func:`xarray.plot` as `air.isel(lon=10, lat=[19,21,22]).plot(hue='lat')`.




Dimension along y-axis
~~~~~~~~~~~~~~~~~~~~~~

Expand All @@ -224,8 +222,8 @@ It is also possible to make line plots such that the data are on the x-axis and
@savefig plotting_example_xy_kwarg.png
air.isel(time=10, lon=[10, 11]).plot(y='lat', hue='lon')

Changing Axes Direction
-----------------------
Other axes kwargs
-----------------

The keyword arguments ``xincrease`` and ``yincrease`` let you control the axes direction.

Expand All @@ -234,6 +232,9 @@ The keyword arguments ``xincrease`` and ``yincrease`` let you control the axes d
@savefig plotting_example_xincrease_yincrease_kwarg.png
air.isel(time=10, lon=[10, 11]).plot.line(y='lat', hue='lon', xincrease=False, yincrease=False)

In addition, one can use ``xscale, yscale`` to set axes scaling; ``xticks, yticks`` to set axes ticks and ``xlim, ylim`` to set axes limits. These accept the same values as the matplotlib methods ``Axes.set_(x,y)scale()``, ``Axes.set_(x,y)ticks()``, ``Axes.set_(x,y)lim()`` respectively.


Two Dimensions
--------------

Expand Down
3 changes: 3 additions & 0 deletions doc/whats-new.rst
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,9 @@ Documentation
Enhancements
~~~~~~~~~~~~

- :py:meth:`plot()` now accepts the kwargs ``xscale, yscale, xlim, ylim, xticks, yticks`` just like Pandas. Also ``xincrease=False, yincrease=False`` now use matplotlib's axis inverting methods instead of setting limits.
By `Deepak Cherian <https://github.com/dcherian>`_. (:issue:`2224`)

- DataArray coordinates and Dataset coordinates and data variables are
now displayed as `a b ... y z` rather than `a b c d ...`.
(:issue:`1186`)
Expand Down
96 changes: 76 additions & 20 deletions xarray/plot/plot.py
Original file line number Diff line number Diff line change
Expand Up @@ -270,6 +270,10 @@ def line(darray, *args, **kwargs):
Coordinates for x, y axis. Only one of these may be specified.
The other coordinate plots values from the DataArray on which this
plot method is called.
xscale, yscale : 'linear', 'symlog', 'log', 'logit', optional
Specifies scaling for the x- and y-axes respectively
xticks, yticks : Specify tick locations for x- and y-axes
xlim, ylim : Specify x- and y-axes limits
xincrease : None, True, or False, optional
Should the values on the x axes be increasing from left to right?
if None, use the default for the matplotlib function.
Expand Down Expand Up @@ -305,8 +309,14 @@ def line(darray, *args, **kwargs):
hue = kwargs.pop('hue', None)
x = kwargs.pop('x', None)
y = kwargs.pop('y', None)
xincrease = kwargs.pop('xincrease', True)
yincrease = kwargs.pop('yincrease', True)
xincrease = kwargs.pop('xincrease', None) # default needs to be None
yincrease = kwargs.pop('yincrease', None)
xscale = kwargs.pop('xscale', None) # default needs to be None
yscale = kwargs.pop('yscale', None)
xticks = kwargs.pop('xticks', None)
yticks = kwargs.pop('yticks', None)
xlim = kwargs.pop('xlim', None)
ylim = kwargs.pop('ylim', None)
add_legend = kwargs.pop('add_legend', True)
_labels = kwargs.pop('_labels', True)
if args is ():
Expand Down Expand Up @@ -343,7 +353,8 @@ def line(darray, *args, **kwargs):
xlabels.set_rotation(30)
xlabels.set_ha('right')

_update_axes_limits(ax, xincrease, yincrease)
_update_axes(ax, xincrease, yincrease, xscale, yscale,
xticks, yticks, xlim, ylim)

return primitive

Expand Down Expand Up @@ -378,37 +389,69 @@ def hist(darray, figsize=None, size=None, aspect=None, ax=None, **kwargs):
"""
ax = get_axis(figsize, size, aspect, ax)

xincrease = kwargs.pop('xincrease', None) # default needs to be None
yincrease = kwargs.pop('yincrease', None)
xscale = kwargs.pop('xscale', None) # default needs to be None
yscale = kwargs.pop('yscale', None)
xticks = kwargs.pop('xticks', None)
yticks = kwargs.pop('yticks', None)
xlim = kwargs.pop('xlim', None)
ylim = kwargs.pop('ylim', None)

no_nan = np.ravel(darray.values)
no_nan = no_nan[pd.notnull(no_nan)]

primitive = ax.hist(no_nan, **kwargs)

ax.set_ylabel('Count')

ax.set_title('Histogram')
ax.set_xlabel(label_from_attrs(darray))

_update_axes(ax, xincrease, yincrease, xscale, yscale,
xticks, yticks, xlim, ylim)

return primitive


def _update_axes_limits(ax, xincrease, yincrease):
def _update_axes(ax, xincrease, yincrease,
xscale=None, yscale=None,
xticks=None, yticks=None,
xlim=None, ylim=None):
"""
Update axes in place to increase or decrease
For use in _plot2d
Update axes with provided parameters
"""
if xincrease is None:
pass
elif xincrease:
ax.set_xlim(sorted(ax.get_xlim()))
elif not xincrease:
ax.set_xlim(sorted(ax.get_xlim(), reverse=True))
elif xincrease and ax.xaxis_inverted():
ax.invert_xaxis()
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is there a reason why we weren't using these methods earlier?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think so!

elif not xincrease and not ax.xaxis_inverted():
ax.invert_xaxis()

if yincrease is None:
pass
elif yincrease:
ax.set_ylim(sorted(ax.get_ylim()))
elif not yincrease:
ax.set_ylim(sorted(ax.get_ylim(), reverse=True))
elif yincrease and ax.yaxis_inverted():
ax.invert_yaxis()
elif not yincrease and not ax.yaxis_inverted():
ax.invert_yaxis()

# The default xscale, yscale needs to be None.
# If we set a scale it resets the axes formatters,
# This means that set_xscale('linear') on a datetime axis
# will remove the date labels. So only set the scale when explicitly
# asked to. https://github.com/matplotlib/matplotlib/issues/8740
if xscale is not None:
ax.set_xscale(xscale)
if yscale is not None:
ax.set_yscale(yscale)

if xticks is not None:
ax.set_xticks(xticks)
if yticks is not None:
ax.set_yticks(yticks)

if xlim is not None:
ax.set_xlim(xlim)
if ylim is not None:
ax.set_ylim(ylim)


# MUST run before any 2d plotting functions are defined since
Expand Down Expand Up @@ -500,6 +543,10 @@ def _plot2d(plotfunc):
If passed, make column faceted plots on this dimension name
col_wrap : integer, optional
Use together with ``col`` to wrap faceted plots
xscale, yscale : 'linear', 'symlog', 'log', 'logit', optional
Specifies scaling for the x- and y-axes respectively
xticks, yticks : Specify tick locations for x- and y-axes
xlim, ylim : Specify x- and y-axes limits
xincrease : None, True, or False, optional
Should the values on the x axes be increasing from left to right?
if None, use the default for the matplotlib function.
Expand Down Expand Up @@ -577,7 +624,8 @@ def newplotfunc(darray, x=None, y=None, figsize=None, size=None,
cmap=None, center=None, robust=False, extend=None,
levels=None, infer_intervals=None, colors=None,
subplot_kws=None, cbar_ax=None, cbar_kwargs=None,
**kwargs):
xscale=None, yscale=None, xticks=None, yticks=None,
xlim=None, ylim=None, **kwargs):
# All 2d plots in xarray share this function signature.
# Method signature below should be consistent.

Expand Down Expand Up @@ -723,11 +771,17 @@ def newplotfunc(darray, x=None, y=None, figsize=None, size=None,
raise ValueError("cbar_ax and cbar_kwargs can't be used with "
"add_colorbar=False.")

_update_axes_limits(ax, xincrease, yincrease)
_update_axes(ax, xincrease, yincrease, xscale, yscale,
xticks, yticks, xlim, ylim)

# Rotate dates on xlabels
# Do this without calling autofmt_xdate so that x-axes ticks
# on other subplots (if any) are not deleted.
# https://stackoverflow.com/questions/17430105/autofmt-xdate-deletes-x-axis-labels-of-all-subplots
if np.issubdtype(xval.dtype, np.datetime64):
ax.get_figure().autofmt_xdate()
for xlabels in ax.get_xticklabels():
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Missed this bit in an older PR.

xlabels.set_rotation(30)
xlabels.set_ha('right')

return primitive

Expand All @@ -739,7 +793,9 @@ def plotmethod(_PlotMethods_obj, x=None, y=None, figsize=None, size=None,
add_labels=True, vmin=None, vmax=None, cmap=None,
colors=None, center=None, robust=False, extend=None,
levels=None, infer_intervals=None, subplot_kws=None,
cbar_ax=None, cbar_kwargs=None, **kwargs):
cbar_ax=None, cbar_kwargs=None,
xscale=None, yscale=None, xticks=None, yticks=None,
xlim=None, ylim=None, **kwargs):
"""
The method should have the same signature as the function.

Expand Down
69 changes: 65 additions & 4 deletions xarray/tests/test_plot.py
Original file line number Diff line number Diff line change
Expand Up @@ -426,10 +426,6 @@ def test_xlabel_uses_name(self):
self.darray.plot.hist()
assert 'testpoints [testunits]' == plt.gca().get_xlabel()

def test_ylabel_is_count(self):
self.darray.plot.hist()
assert 'Count' == plt.gca().get_ylabel()

def test_title_is_histogram(self):
self.darray.plot.hist()
assert 'Histogram' == plt.gca().get_title()
Expand Down Expand Up @@ -1675,3 +1671,68 @@ def test_plot_cftime_data_error():
data = DataArray(data, coords=[np.arange(5)], dims=['x'])
with raises_regex(NotImplementedError, 'cftime.datetime'):
data.plot()


test_da_list = [DataArray(easy_array((10, ))),
DataArray(easy_array((10, 3))),
DataArray(easy_array((10, 3, 2)))]


@requires_matplotlib
class TestAxesKwargs(object):
@pytest.mark.parametrize('da', test_da_list)
@pytest.mark.parametrize('xincrease', [True, False])
def test_xincrease_kwarg(self, da, xincrease):
plt.clf()
da.plot(xincrease=xincrease)
assert plt.gca().xaxis_inverted() == (not xincrease)

@pytest.mark.parametrize('da', test_da_list)
@pytest.mark.parametrize('yincrease', [True, False])
def test_yincrease_kwarg(self, da, yincrease):
plt.clf()
da.plot(yincrease=yincrease)
assert plt.gca().yaxis_inverted() == (not yincrease)

@pytest.mark.parametrize('da', test_da_list)
@pytest.mark.parametrize('xscale', ['linear', 'log', 'logit', 'symlog'])
def test_xscale_kwarg(self, da, xscale):
plt.clf()
da.plot(xscale=xscale)
assert plt.gca().get_xscale() == xscale

@pytest.mark.parametrize('da', [DataArray(easy_array((10, ))),
DataArray(easy_array((10, 3)))])
@pytest.mark.parametrize('yscale', ['linear', 'log', 'logit', 'symlog'])
def test_yscale_kwarg(self, da, yscale):
plt.clf()
da.plot(yscale=yscale)
assert plt.gca().get_yscale() == yscale

@pytest.mark.parametrize('da', test_da_list)
def test_xlim_kwarg(self, da):
plt.clf()
expected = (0.0, 1000.0)
da.plot(xlim=[0, 1000])
assert plt.gca().get_xlim() == expected

@pytest.mark.parametrize('da', test_da_list)
def test_ylim_kwarg(self, da):
plt.clf()
da.plot(ylim=[0, 1000])
expected = (0.0, 1000.0)
assert plt.gca().get_ylim() == expected

@pytest.mark.parametrize('da', test_da_list)
def test_xticks_kwarg(self, da):
plt.clf()
da.plot(xticks=np.arange(5))
expected = np.arange(5).tolist()
assert np.all(plt.gca().get_xticks() == expected)

@pytest.mark.parametrize('da', test_da_list)
def test_yticks_kwarg(self, da):
plt.clf()
da.plot(yticks=np.arange(5))
expected = np.arange(5)
assert np.all(plt.gca().get_yticks() == expected)