Barh Ignoring xlim

I have a DataFrame where I want to plot the barh with a limited vertical axis:

n = 10
tmp_df = pd.DataFrame({"x": np.arange(n) + 1, "y": np.random.rand(n)})
tmp_df.hvplot.barh("x", "y", xlim=(0, 5))

It isn’t clear to me why xlim(0, 5) is being ignored. When I change this to ylim(0, 0.5) then the horizontal axis is constrained as expected. Does anybody have any suggestions for constraining the xlim for a barh?

The problem is that the axis labeled x is converted to a CategoricalAxis, which does not work with xlim as it is a list of strings.

My solution to constraining the axis will be using a hook like this:

import pandas as pd
import numpy as np
import hvplot.pandas
from functools import partial


def hook(plot, element, xlim):
    plot.handles["y_range"].factors = list(map(str, range(xlim[0], xlim[1] + 1)))


n = 10
tmp_df = pd.DataFrame({"x": np.arange(n) + 1, "y": np.random.rand(n)})
tmp_df.hvplot.barh("x", "y").opts(hooks=[partial(hook, xlim=(0, 5))])

3 Likes

Hi @seanlaw !

Yes this has to do with the axis of a bar plot being categorical (here you’ve got numbers, but you could have an axis that is something like ['Appled', 'Banana', 'Pear']).

There’s another workaround to this issue. hvplot returns objects that are holoviews objects which are not plots but wrappers around your data, and that when displayed in a notebook are turned into plots. That’s a major difference with Matplotlib for instance, with which you get a plot object (Figure/Axes) and can’t do anything with your data anymore. It happens that holoviews objects can be indexed/sliced (Indexing and Selecting Data — HoloViews 1.14.5 documentation), most of its objects support the familiar .iloc method:

import numpy as np
import pandas as pd

import hvplot.pandas

n = 10
tmp_df = pd.DataFrame({"x": np.arange(n) + 1, "y": np.random.rand(n)})
tmp_df.hvplot.barh("x", "y").iloc[:5]

But anyway, I think that xlim having no effect here is an issue and that it should be fixed, either in holoviews or hvplot directly.

3 Likes

But anyway, I think that xlim having no effect here is an issue and that it should be fixed, either in holoviews or hvplot directly.

I’ve created hvplot.bar ignores xlim · Issue #946 · holoviz/hvplot · GitHub to track this issue.

1 Like