使用基本图形重新创建ggplot2 geom_point()

时间:2012-07-26 22:33:29

标签: r plot ggplot2

我有以下ggplot2代码,我想使用基本图形而不是ggplot2来生成类似的输出 - 但我似乎无法找到一种方法来区分多个“属性”与正常情节。我错过了什么:

GGPLOT2:

ggplot(data.df, aes(x=Axis1, y=Axis2, shape=Plant, color=Type)) +
geom_point()

我的情节尝试(内联帮助让我有点相似):

data.ma <- as.matrix(data.df)

plot(range(data.ma[,6]), range(data.ma[,7]),xlab="Axis 1",ylab="Axis 2")
points(data.ma[data.ma[,1] == 'Plant1',6],
   data.ma[data.ma[,1] == 'Plant1',7], pch=2)
points(data.ma[data.ma[,1] == 'Plant2',6],
   data.ma[data.ma[,1] == 'Plant2',7], pch=3)
legend(0,legend=c("Plant1","Plant2"))

这给了我一个图,其中至少可以在图中区分“植物”类型,但它似乎很复杂,我无法弄清楚如何根据“类型”更改所有点的颜色“排。

有什么建议吗?

编辑 - 一个数据示例//我意识到我第一次尝试使用情节甚至没有给出正确的例子:(:

library(ggplot2)
data.df <- data.frame(
  Plant=c('Plant1','Plant1','Plant1','Plant2','Plant2','Plant2'),
  Type=c(1,2,3,1,2,3),
  Axis1=c(0.2,-0.4,0.8,-0.2,-0.7,0.1),
  Axis2=c(0.5,0.3,-0.1,-0.3,-0.1,-0.8)
)


ggplot(data.df, aes(x=Axis1, y=Axis2, shape=Plant, color=Type)) +
geom_point()

data.ma <- as.matrix(data.df)
plot(range(data.ma[,3]), range(data.ma[,4]),xlab="Axis 1",ylab="Axis 2")
points(data.ma[data.ma[,1] == 'Plant1',3],
       data.ma[data.ma[,1] == 'Plant1',4], pch=2)
points(data.ma[data.ma[,1] == 'Plant2',3],
       data.ma[data.ma[,1] == 'Plant2',4], pch=3)
legend(0,legend=c("Plant1","Plant2"))

2 个答案:

答案 0 :(得分:4)

我正准备发布这个,然后我看到Justin击败了很多。无论如何,这包括一些基本的传说:

color_foo <- colorRampPalette(c('lightblue','darkblue'))
colors <- color_foo(3)

plot(range(data.df[,3]), range(data.df[,4]),
        xlab="Axis 1",ylab="Axis 2",type = "n")
points(data.df$Axis1,data.df$Axis2,
        pch=c(3,4)[data.df$Plant],
        col = colors[data.df$Type])
legend("topright",legend=c("Plant1","Plant2"),pch = 3:4)
legend("bottomright",legend=c("Type1","Type2","Type3"),
        pch = 20,col = colors)

enter image description here

答案 1 :(得分:3)

使用基础图和您的数据集:

with(data.df, 
     plot(x = Axis1, 
          y = Axis2, 
          col = factor(Type),                 
          pch = as.integer(factor(Plant))))

这样做你正在寻找什么?我会把这个传说留作读者的练习......