【问题标题】:y-axis scaling in seaborn vs pandasseaborn vs pandas中的y轴缩放
【发布时间】:2016-08-04 09:43:29
【问题描述】:

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

如果我将 y 轴值乘以 10^6,它们会正确显示,但使用seaborn 绘制时的实际值在seaborn 生成的图中仍然不可见/无法区分。

我如何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'])

【问题讨论】:

  • 不清楚你所说的“y 轴保持不可见”是什么意思,也无法运行你的代码...

标签: python pandas seaborn


【解决方案1】:

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

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

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

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))

然后绘制 logspeed 而不是 speed。

另一种方法是使用 seaborn regplot instead

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

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

【讨论】:

  • 但这会丢失信息,我会得到日志值而不是正常值,并且会扭曲比例/相对值。另外,lowess fit 只是事后的想法,主要是我想得到一个散点图。
  • 我怎样才能复制我可以通过pandas 接口到matplotlib,但使用seaborn 实现的功能?
  • 编辑答案以包含 matplotlib 解决方案。
【解决方案2】:

奇怪的是 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

【讨论】:

  • @mwaskom 这个答案解决了我面临的问题,值太小,似乎变得几乎不可见。
  • Markus 如何显示校正轴限制的最终图?我正在使用 Spyder,提示不会更新或绘制新图。我是 python 业务的新手,不知道如何显示更新的情节。
猜你喜欢
  • 2015-01-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-27
  • 1970-01-01
  • 2022-01-11
  • 1970-01-01
相关资源
最近更新 更多