-1

I am plotting some data with

g = seaborn.displot(data, x=var, stat='probability')

# Set appropriate ticks                   
plt.xticks(np.arange(0, int(data[var].max() + 1), 1.0))
plt.show()

which is giving me the desired plot:

enter image description here

But I would like to compress the axis to remove the unnecessary space and I'm struggling to work out how.

A. Bollans
  • 149
  • 1
  • 10
  • Check [here](https://stackoverflow.com/questions/44222066/how-to-put-bars-close-to-each-other-in-a-seaborns-factorplot-when-comparing-1-v) and [here](https://www.tutorialspoint.com/how-to-remove-gaps-between-bars-in-matplotlib-bar-chart) - maybe you'll find the answer. – Beholder Jul 22 '22 at 11:25

1 Answers1

2

You can increase the margins that determine the space added at both sides of the data limit to get the view limit. Default is 0.05.

plt.margins(x=0.5)

enter image description here


As pointed out by JohanC in the comment below: if your data are discrete values you may specify discrete=True or cast your data to strings to plot them as categories (in the latter case you don't need to set the ticks manually).

sns.displot(data[var].astype(str), stat='probability')

enter image description here

Stef
  • 28,728
  • 2
  • 24
  • 52
  • 1
    The main problem is that OP forgot to add `discrete=True` for these discrete data. A histogram default uses settings for continuous data, which don't make sense here. – JohanC Jul 22 '22 at 12:07
  • @JohanC: right, would you post this as an answer, so that I can delete my answer. – Stef Jul 22 '22 at 12:21
  • You can update yours – JohanC Jul 22 '22 at 12:29
  • IMO prefer `discrete=True` over `.astype(str)` as the former generalizes across the different ways of invoking `displot`/`histplot`. – mwaskom Jul 22 '22 at 17:01
  • 1
    @mwaskom with `discrete=True` and numerical data you need to set the ticks as shown in the OP, see [this example](https://i.stack.imgur.com/jpUoa.png), whereas with categorical data you directly get a neatly formatted x-axis. – Stef Jul 23 '22 at 08:20
  • That's a good point. Well, either way, you don't need to pass `data` and `x=data[x_var]`. – mwaskom Jul 23 '22 at 13:16
  • @mwaskom yes, this was a leftover from the original example. Changed it in the answer, thanks. – Stef Jul 23 '22 at 19:07