Seaborn lineplot logarithmic scale
Asked Answered
D

2

17

I'm having a problem with adding a logarithmic X-axis to my plot. I want to show results based on the sample size with methods A, B and C.

My dataframe result:

            A         B         C
15   0.733333  0.613333  0.733333
30   0.716667  0.693333  0.766667
59   0.733684  0.678485  0.745763
118  0.796667  0.726087  0.779661
236  0.817862  0.788333  0.838983
470  0.832125  0.814468  0.836170

What I'm trying to make work:

sample_count = np.around(np.logspace(math.log10(15),math.log10(470),6))
sample_count = sample_count.astype(int)

sns.set_style('whitegrid')
g_results=sns.lineplot(data=results,dashes=0,markers=['o','o','o'])
g_results.set(xticks=sample_count)
g_results.set(xscale='log')

However the result is not what I exactly want, as the ticks are completely gone:

current output

Without the last xscale line it looks like this, which is the linear scale of course, but this time with the correct ticks:

current output without xscale

What I want to achieve is something like this:

desired output

How do I get my desired output?

Dramatist answered 10/11, 2020 at 12:45 Comment(1)
The title of this question should be changed to indicate that only the x axis is talked about here, I came for the y axis, to no avail.Contessacontest
D
19

First set the scale for the x-axis to logarithmic and then set xticks and labels as you want.

sns.set_style('whitegrid')
g_results=sns.lineplot(data=results,dashes=0,markers=['o','o','o'])
g_results.set(xscale='log')
g_results.set(xticks=sample_count)
g_results.set(xticklabels=sample_count)

This gives you this result:

resulting figure

Note that I'm using sample_count as defined with the logarithmic scale:

sample_count = np.around(np.logspace(math.log10(15),math.log10(470),6))
Desolate answered 10/11, 2020 at 13:55 Comment(0)
A
0

Apart from setting the xticklabels as in @Davide Anghileri's answer, you can also format the tick values as a number using matplotlib.ticker.ScalarFormatter.

import seaborn as sns
from matplotlib.ticker import ScalarFormatter

sns.set_style('whitegrid')
ax = sns.lineplot(data=results, dashes=0, markers=['o','o','o'])
ax.set(xscale='log', xticks=[15, 30, 59, 118, 236, 470])
ax.xaxis.set_major_formatter(ScalarFormatter())

result


If you want to log-scale the y-axis, it works exactly the same; simply use yaxis instead of xaxis and yscale instead of xscale.

data = pd.Series([15, 30, 59, 118, 236, 470])

ax = sns.lineplot(data=data)
ax.set(yscale='log', yticks=data)               # <--- logscale y-axis / set tick locations
ax.yaxis.set_major_formatter(ScalarFormatter()) # <--- format y-axis tick values
Archipenko answered 18/2 at 4:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.