0

I am trying to make some plots with Matplotlib and Seaborn. I would like the y ticks to go from 0 to 1. As you can see in the screenshot though, the plots are being rescaled which makes them harder to compare visually. How can I force each plot's y ticks to run from 0 to 1?

category_types = list(preds_df['category'].value_counts().keys())

fig = plt.figure(figsize=(12, 18))
fig.subplots_adjust(hspace=0.3,wspace=0.3,left=0,right=1,bottom=0, top=1)
Npicture = 6

count = 1
for irow in range(Npicture):
    ax = fig.add_subplot(3, 2, count,xticks=[],yticks=[])
    ax.set_title(category_types[count-1])
    plt.yticks(np.arange(0, 1, step=0.1))
    sns.boxplot(ax=ax, x="variable", y="value", data=pd.melt(preds_df[preds_df['category'] == category_types[count-1]][labels]))
    count += 1
plt.show()

enter image description here

Henry Dashwood
  • 143
  • 1
  • 2
  • 13
  • Possible duplicate of [Python, Matplotlib, subplot: How to set the axis range?](https://stackoverflow.com/questions/2849286/python-matplotlib-subplot-how-to-set-the-axis-range) – wwii May 14 '19 at 17:58

1 Answers1

0

I'll answer my own question, in case anyone has the same problem. It turns out if you swap the lines

plt.yticks(np.arange(0, 1, step=0.1))
sns.boxplot(ax=ax, x="variable", y="value", data=pd.melt(preds_df[preds_df['category'] == category_types[count-1]][labels]))

so the code becomes

sns.boxplot(ax=ax, x="variable", y="value", data=pd.melt(preds_df[preds_df['category'] == category_types[count-1]][labels]))
plt.yticks(np.arange(0, 1.1, step=0.1))

it solves the problem enter image description here

Note that I also changed the second argument in plt.yticks() from 1 to 1.1. Leaving it at 1 causes the axis to stop at 0.9.

Update As @user2357112 points out. np.linspace() is a better method to use than np.arange(). So the line should actually read:

plt.yticks(np.linspace(0, 1, 11))
Henry Dashwood
  • 143
  • 1
  • 2
  • 13
  • 1
    Instead of `arange`, you should use `np.linspace`. Using `arange` opens you up to more boundary errors because of floating-point rounding, while `linspace` guarantees you get exactly the number of steps you want. For example, `arange(0, 1, 0.1)` doesn't include `1.0`, but `arange(1, 1.3, .1)` includes `1.3`. With `linspace`, you don't have that kind of problem. The right endpoint is always there unless you explicitly say to leave it out. – user2357112 May 14 '19 at 18:07