I would like to make a scatter plot where I can set my y_scale and have it look like this
However, when I use
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
sns.scatterplot(data=df, y=df['y_target'], x=df['x_variable'], hue='cat')
I get this. I can only set the y_ticks but it doesn't change how the image is scaled. Is there anyway to do this in seaborn? I can set the scale to logarithmic and get a better representation with the image below. However, I still can't modify the y_ticks.
g = sns.scatterplot(data=df, y=df['y_target'], x=df['x_variable'], hue='cat')
g.set_yscale("log")
You need to "catch" the subplot on which in the scatterplot was created with ax = sns.scatterplot(...)
. Then you need to set both the logscale and the desired ticks.
You can format the ticks either by explicitly setting ax.set_yticklabels(...)
or by using the FormatStrFormatter
.
import matplotlib.pyplot as plt
from matplotlib.ticker import FormatStrFormatter
import seaborn as sns
import numpy as np
import pandas as pd
df = pd.DataFrame({'x_variable': np.random.uniform(-6, 6, 200),
'y_target': 10 ** np.random.uniform(-1.6, 3, 200),
'cat': np.random.choice([*'ABCD'], 200)})
ax = sns.scatterplot(data=df, y=df['y_target'], x=df['x_variable'], hue='cat', hue_order=[*'ABCD'])
ax.set_yscale('log')
ax.set_yticks([0.03, 0.1, 0.3, 1, 3, 10, 30, 100, 300, 1000])
# ax.set_yticklabels([0.03, 0.1, 0.3, 1, 3, 10, 30, 100, 300, 1000])
ax.yaxis.set_major_formatter(FormatStrFormatter('%g'))
plt.tight_layout()
plt.show()