Set y ticks in logscale Boxplots: Matplotlib

317 Views Asked by At

I am plotting boxplots of some data in the range of 0 to 20 on a log scale. I want to set a custom starting and ending ticks. All the other ticks should be in the log scale aswell (2 * 10^-1).

I tried using ax.yaxis.set_major_formatter(ticker.FuncFormatter(lambda y, _: '{:g}'.format(y))) doesn't work
Also

ymin = min - 0.1 * (max - min)
ymax = max + 0.1 * (max - min)
plt.ylim(ymin, ymax)

gives the warning:

Invalid limit will be ignored.
  plt.ylim(ymin, ymax)

here is the entire code:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from matplotlib import ticker
from math import log, exp

log_scale = True
min = 0
max = 50

atributes = []
for i in [8, 10, 6, 12]:
    att = [i] * 50
    atributes.extend(att)
values = np.random.uniform(1, 20, 200)

df1 = pd.DataFrame({'Attributes': atributes, 'values': values})
if min is None and max is not None:
    min = df1["values"].min()
if max is None and min is not None:
    max = df1["values"].max()

if min or max is not None:
    df1 = df1[(min <= df1["values"]) & (df1["values"] <= max)]

plt.figure()
sns.set_style("whitegrid")
ax = None

ax = sns.boxplot(x='Attributes', y='values', data=df1, color="white")

if log_scale:
    plt.yscale('log')
    ax.yaxis.set_major_formatter(ticker.FuncFormatter(lambda y, _: '{:g}'.format(y)))

if min is not None:
    try:
        min, max = log(min), log(max)
    except ValueError:
        min = 0
        max = log(max)
    ymin = min - 0.1 * (max - min)
    ymax = max + 0.1 * (max - min)
    plt.ylim(exp(ymin), exp(ymax))

fig = plt.gcf()
fig.set_size_inches(10.5, 8)
plt.show()

Here is how the plot looks like:

Boxplot of atributes

0

There are 0 best solutions below