Search code examples
pythonmatplotlibseabornscientific-notationrelplot

How to show scientific notation


I have a seaborn relplot. I want to show scientific notation. Presently the image takes large space on x and y ticks. I want to minimize it by converting the axis to scientific notation.

My code:

sns.relplot(x='Vmpp',y='cVmpp',data=cdf)

enter image description here

My solution and present output:

#I tried a solution reported for the seaborn heatmap. It did produce a plot (I think heat plot?) but did not work. 
sns.relplot(x='Vmpp',y='cVmpp',data=cdf,fmt='.2g')

Present output:

AttributeError: 'PathCollection' object has no property 'fmt'

enter image description here


Solution

  • sns.relplot() is a figure-level function. If you just need the simple scatter plot, you may want to use sns.scatterplot() instead.

    In any case, you can fine-tune the plot in the usual matplotlib ways. In particular, scientific notation for any tick label numbers can be forced with ax.ticklabel_format(axis='both', style='scientific', scilimits=(0, 0)).

    I would also recommend setting the alpha value, because you have many overlapping points. Here's a complete example:

    import matplotlib.pyplot as plt
    import seaborn as sns
    
    sns.set()
    titanic = sns.load_dataset('titanic')
    
    fig, ax = plt.subplots()
    ax.ticklabel_format(axis='both', style='scientific', scilimits=(0, 0))
    sns.scatterplot(x='age', y='fare', data=titanic, alpha=0.5);
    

    enter image description here

    Edit: As @mwaskom points out, you can change the tick labels in this way with sns.relplot() too, just call the plotting function before the formatter in this case. You don't need to specify the axes, because ticklabel_format() works via the matplotlib.pyplot interface too:

    # [...] imports and data as above 
    
    sns.relplot(x='age', y='fare', data=titanic, alpha=0.5)
    plt.ticklabel_format(axis='both', style='scientific', scilimits=(0, 0));