[英]How to create multiple series scatter plot with connected points using seaborn?
我有一组存储在熊猫数据框中的数据。 我正在尝试使用 seaborn 的 pointplot() 创建具有连接点的多系列散点图。 每个系列都有不同的 (x,y) 值,它们以浮点数形式存储在我的数据框中。 每行都有一个标签,用于区分每个系列。 我使用的是 Python 2.7、seaborn 0.5.1 版和 matplotlib 1.4.3 版。
我设法找到的一切都告诉我,我可以通过以下方式实现这一目标:
import matplotlib.pyplot as plt
import seaborn as sns
# Suppose my dataframe is called 'df', with columns 'x', 'y', and 'label'.
sns.pointplot(x = 'x', y = 'y', hue = 'label', data = df)
然而,这会导致一些奇怪的行为:
我试图通过将我的数据框分成几部分来解决这个问题。 这并不理想,因为我可能有大约 10 个以上的系列要同时绘制,而且我不希望手动拆分数据:
df1 = df[df.test_type.values == "label 1"]
df2 = df[df.test_type.values == "label 2"]
ax = sns.pointplot(x = 'x',y='y', color = "blue", data = df1)
sns.pointplot(x = 'x', y = 'y', data = df2, color="red", ax = ax)
在这种情况下,所有点都连接在一起并且它们被适当地着色,但同样,x 轴表现出非常奇怪的行为。 即使我的每个数据框中的 x 值不同,绘图也会对齐它们,使它们看起来相同。
现在,我不确定如何干净地发布我的输出/绘图,但是可以使用以下内容重新创建我的一些问题:
#import the necessary modules
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
#Here is some sample data. The 'x2' data is slightly offset from 'x1'
x1 = range(0,100,10)
x2 = range(1,100,10)
x = x1+x2
#The y-values I generate here mimic the general shape of my actual data
y1 = x1[::-1]
y2 = [i+25 for i in x1[::-1]]
y = y1+y2
#Two levels of labels that will be applied to the data
z1 = ["1"]*10
z2 = ["2"]*10
z = z1+z2
#A pandas data frame from the above data
df = pd.DataFrame({'x': x, 'y': y, 'z': z})
#Pointplot using the above data
sns.pointplot(x = 'x', y = 'y', data = df, hue = 'z')
运行此代码会产生以下结果:
总结一下我的问题:
是否有更简单/更好/更优雅的方法来使用存储在 Pandas 数据框中的数据绘制具有连接点的多系列散点图? Seaborn 的点图看起来很理想,但它并没有像我预期的那样运行,我怀疑它的用途可能与我需要完成的目的不同。 我对可以实现这一点的其他解决方案持开放态度(最好使用 python)。
提前致谢。 如果我能弄清楚如何从我的代码上传输出和绘图,我会更新我的问题。
我是 stackoverflow 的 100% 新手。 我很想通过发布我的代码生成的图来澄清我的问题,但我无法弄清楚。 任何有关如何执行此操作的指示也将不胜感激,因此我可以更新问题。
编辑:事实证明,seaborn 的点图使用 x 轴作为分类轴,这解释了我上面提到的奇怪行为。 有没有办法手动将 x 轴行为从分类更改为数值? 这似乎是最简单的方法,但我对 python 中的微调图不是很熟悉。
我有一个类似的问题,我最终使用 Seaborn 的FacetGrid解决了它。 我使用 plt.scatter 作为点,使用 plt.plot 作为连接点的线。
g = sns.FacetGrid(df, hue="z", size=8)
g.map(plt.scatter, "x", "y")
g.map(plt.plot, "x", "y")
请注意,这是在 Seaborn 0.6.0 版和 0.5.1 版中完成的。
在@mwaskom 和这个问题的帮助下,我设法找到了我发布的问题的解决方案:
#Assuming df is a pandas data frame with columns 'x', 'y', and 'label'
for key,grp in df.groupby('label'):
plt.plot(grp.x,grp.y,'o-',label = key)
plt.legend(loc = 'best')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.