更改seaborn图中轴的单位

-2 投票
1 回答
36 浏览
提问于 2025-04-14 15:46

我正在绘制一些与距离相关的函数,这些函数会随着特定的距离而波动。我希望x轴的单位能够以这个特定距离来表示。比如说,如果这个特定距离是200米,那么我希望在x轴上x=50时显示为0.25,x=100时显示为0.5,依此类推。

这是我目前的代码:

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 个回答

0

我想你是在找 plt.xticks() 这个函数(另外还有 ax.set_xticks())。

在你的代码里,你可以加上以下这一行:

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

这里的 ticks 是你数据中的数值,而 labels 是你想在坐标轴上显示的数值。

撰写回答