Skip to content
Advertisement

How to define breaks of the bins for log scale in Seaborn

Consider the following minimal working example:

import numpy as np
import pandas as pd
import seaborn as sns

df = pd.DataFrame({
    "Area":[0.5, 0.05, 0.005]
})

sns.histplot(
    data=df,
    x="Area",
    bins=3,
    log_scale=True
)

The minimal working example above will produce

Seaborn histogram with log scale

Now, let’s use our own breaks of the bins:

sns.histplot(
    data=df,
    x="Area",
    bins=np.logspace(-3, 0, num=4),
    log_scale=True
)

I expected to produce a histogram similar to the one before but I’m getting

enter image description here

What am I doing wrongly? Or is this a bug with Seaborn 0.11.2?

Advertisement

Answer

Apparently, you have to give the bins on the log scale. I.e. with bins=np.logspace(-3, 0, 4) you’re getting bins at 10**np.logspace(-3, 0, 4). Use linspace instead and you should be getting what you’re looking for. bins=np.linspace(-3, 0, 4) gives breaks at 10**np.linspace(-3, 0, 4):

sns.histplot(
    data=df,
    x="Area",
    bins=np.linspace(-3, 0, num=4),
    log_scale=True
)
Advertisement