Changing the units of an axis on a seaborn plot

38 Views Asked by At

I'm plotting some functions of distance where the functions oscillate with a characteristic distance, and I'd like the units of the x-axis to be in terms of this characteristic distance. For example if the characteristic distance is 200m metres, I want x=50 on the x-axis to be 0.25, x=100 to be 0.5 and so on.

Here's my code at the moment:

import seaborn as sns
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

theta = 0.6
d_mass = 1
energy = 1

L_osc = (4*(np.pi)*energy)/d_mass

osc_constants = d_mass/(4*energy)

def P(x):
    return ((np.sin(2*theta))**2)*((np.sin(osc_constants*x))**2)

def S(x):
    return 1 - P(x)

x = np.linspace(0, 20, 1000)
y1 = P(x)
y2 = S(x)

df = pd.DataFrame(zip(x, y1, y2), columns=['x', 'Oscillation Probability', 'Survival      Probability']).set_index('x')
fig, ax = plt.subplots()

# Plot sns.lineplot() to the ax
sns.set_palette('Set2')
sns.set_style('ticks')
sns.lineplot(df, ax=ax)
ax.set_title('Plotting Functions in Matplotlib', size=14)
ax.set_xlim(0, 20)
ax.set_ylim(0, 1.5)

# Despine the graph
#sns.despine()
plt.show()`
1

There are 1 best solutions below

2
Andre On

I guess you're looking fot the plt.xticks() function (alternatively: ax.set_xticks()).

In your code you could add the following line:

ax.set_xticks(ticks=np.linspace(0,20,5), labels=np.linspace(0,1,5) )

Where ticks correspond to the values in your data, and labels correspond to the values you display on the axis.