3

If we plot very simple histogram:

import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
Z = np.array([1, 2, 2, 2, 2, 2, 2, 3, 4, 5])
sns.histplot(Z, bins = 5)
plt.xticks([1, 2, 3, 4, 5])
plt.show()

we obtain:

enter image description here

my question is - is there any possibility to have those ticks centered with respect to bin? i.e. I want to have tick 1 in the middle of the first bin, tick 2 in the middle of second bin i.e.

Do you know if it is possible?

As suggested in a comments, I used discrete = True and it worked. However, I don't understand why it brakes when it comes to creating subplots:

sns.set(rc={'figure.figsize':(10,15)})
X = np.array([1, 1, 1, 1, 1, 1, 2, 3, 4, 5]) 
Y = np.array([1, 2, 3, 4, 5, 5, 5, 5, 5, 5])
Z = np.array([1, 2, 2, 2, 2, 2, 2, 3, 4, 5])
f, axes = plt.subplots(1, 3)
sns.histplot(X, color = "b", ax = axes[0], discrete = True)
plt.xticks(np.arange(1, 6))
sns.histplot(Y, color = "r", ax = axes[1])
plt.xticks([1, 2, 3, 4, 5])
sns.histplot(Z, bins = 5, color = "g", ax = axes[2])
plt.xticks([1, 2, 3, 4, 5])
plt.show()

enter image description here

Do you know why it happens?

Lucian
  • 351
  • 2
  • 10
  • take a look at https://stackoverflow.com/questions/65351989/how-to-center-the-histogram-bars-around-tick-marks-using-seaborn-displot-stacki –  Jun 13 '22 at 15:32
  • 1
    for integer data as in your case it's easiest to use `discrete`: `sns.histplot(Z, discrete=True)` (no need to specify `plt.xticks(...)`) – Stef Jun 13 '22 at 16:00
  • Thank you very much for your comment. Could you please have a look at my updated question? It seems that `discrete = True` does not seem to work, when considering subplots, whereas it work for single histogram. – Lucian Jun 13 '22 at 16:09
  • why do you think is doesn't work? (you didn't specifiy it for axes[1] and [2]) – Stef Jun 13 '22 at 16:12
  • As you can observe, on the first plot (blue) when its specified there is no effect of it. Moreover, I specified `discrete = True` for all three histograms and the result is the same (it does not center thick in the bin) – Lucian Jun 13 '22 at 16:39
  • You should use the object oriented approach to set the xticks (e.g. `axes[0].set_xticks(np.arange(1, 6))`) and `, discrete=True` should be in each plot. [code and plot](https://i.stack.imgur.com/rblzu.png) – Trenton McKinney Jun 14 '22 at 17:17
  • the `discrete=True` is a life hack :) – seralouk Aug 23 '23 at 07:19

0 Answers0