seaborn 与 pandas 中的 y 轴缩放比例

y-axis scaling in seaborn vs pandas

我正在使用 pandas 数据框绘制散点图。这工作正常,但我想使用 seaborn 主题和特殊功能。当我绘制调用 seaborn 的相同数据点时,y 轴几乎保持不可见。 X 轴值的范围为 5000-15000,而 y 轴值的范围为 [-6:6]*10^-7

如果我将 y 轴值乘以 10^6,它们会正确显示,但是使用 seaborn 绘制时的实际值在 seaborn 生成的图中仍然是 invisible/indistinguishable。

如何 seaborn 使结果图中的 y 轴值自动缩放?

还有一些行甚至包含 NaN,在这种情况下不是,如何在绘图时忽略它,而不是手动清除包含 NaN.

的行

下面是我用来绘制的代码。

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


df = pd.read_csv("datascale.csv")
subdf = df.loc[(df.types == "easy") & (df.weight > 1300), ]

subdf = subdf.iloc[1:61, ]
subdf.drop(subdf.index[[25]], inplace=True) #row containing NaN

subdf.plot(x='length', y='speed', style='s') #scales y-axis correctly

sns.lmplot("length", "speed", data=subdf, fit_reg=True, lowess=True) #doesn't scale y-axis properly

# multiplying by 10^6 displays the plot correctly, in matplotlib
plt.scatter(subdf['length'], 10**6*subdf['speed'])

Seaborn 和 matplotlib 在绘图时应该忽略 NaN 值。您应该可以让它们保持原样。

关于 y 缩放:seaborn 中可能存在错误。

最基本的解决方法仍然是在绘图之前缩放数据。 在绘图之前在数据帧中缩放到微速度,然后改为绘制微速度。

subdf['microspeed']=subdf['speed']*10**6

或者在绘图之前转换为 log y,即

import math
df = pd.DataFrame({'speed':[1, 100, 10**-6]})
df['logspeed'] = df['speed'].map(lambda x: math.log(x,10))

然后绘制对数速度而不是速度。

另一种方法是使用 seaborn regplot instead

Matplot lib 正确地为我缩放和绘制如下:

plt.plot(subdf['length'], subdf['speed'], 'o')

奇怪的是seaborn没有正确缩放轴。尽管如此,您还是可以纠正这种行为。首先,获取对绘图轴对象的引用:

lm = sns.lmplot("length", "speed", data=subdf, fit_reg=True)

之后您可以手动设置 y 轴范围:

lm.axes[0,0].set_ylim(min(subdf.speed), max(subdf.speed))

结果应如下所示:

示例 Jupyter 笔记本 here