重塑/融化散点图的数据框

时间:2012-11-08 18:48:09

标签: r ggplot2 reshape2

我有一个如下所示的数据文件:

x   ys --------------------->
1   20   25   30   12   22   12
2   12    9   12   32   12 
3   33   12   11    6    1
4    5   10   41   12    3
5    7   81   12   31    8   3   4   11

我想用一个x值和多个y值(ys)制作一个散点图。我试图使用熔化重塑,但我无法获得创建这个图的正确数据结构。如何在R中执行此操作并使用ggplot进行绘图?谢谢你的帮助。

2 个答案:

答案 0 :(得分:2)

那么什么不适用于melt?您对geom_point()有什么问题?很难说这是否是你想要的:

library( "reshape2" )
library( "ggplot2" )

df <- data.frame( x = rnorm(20), ya = rnorm(20), yb = rnorm(20), yc = rnorm(20) )
df <- melt(df, id.vars="x", variable.name="class", value.name="y")

ggplot( df, aes( x = x, y = y) ) +
  geom_point( aes(colour = class) )

ggplot( df, aes( x = x, y = y) ) +
  geom_point() +
  facet_wrap( "class" )

答案 1 :(得分:0)

您可以使用matplot功能。

假设您的数据位于名为myDat的对象中,并且x值位于列1中且y值位于其他列中,

matplot(x = myDat[, 1], y = myDat[, -1], type = "p", pch = 21)

会产生类似

的东西

enter image description here

或使用latticeExtra主题的ggplot2like包:

library(latticeExtra)

xyplot(as.formula(paste(paste0(names(myDat)[-1], collapse = "+"), "~",
  names(myDat[1]))),
  data = myDat, par.settings = ggplot2like(), grid = TRUE)

enter image description here