无法使用 ggplot 生成散点图的离散图例

Trouble producing discrete legend using ggplot for a scatterplot

我对 R 中的 ggplot 函数相当陌生。目前,我正在努力为我手工构建的给定数据集生成图例。为简单起见,假设这是我的数据集:

rawdata<-data.frame(matrix(c(1,1,1,
                             2,1,-1,
                             3,-1,-1,
                             4,-1,1
                             4,-2,2),5,3,byrow=TRUE))
names(rawdata)<-c("Town","x-coordinate","y-coordinate")
rawdata[,1]<-as.factor(rawdata[,1])

现在,我正在使用 ggplot 来弄清楚如何在散点图上生成图例。到目前为止,我已经完成了以下工作:

p1<-ggplot(data=rawdata,aes(x=x.coordinate,y=y.coordinate,fill=rawdata[,1]))
+geom_point(data=rawdata,aes(x=x.coordinate,y=y.coordinate))

我使用上面的代码生成以下内容,

As you can see, the coordinates have been plotted and the legend has been constructed, but they are only colored black.

我了解到,要为坐标着色,我需要使用 geom_point 函数中的参数 colour=rawdata[,1] 来以点为单位着色。但是,当我尝试这样做时,出现以下错误代码:

Error: Aesthetics must be either length 1 or the same as the data (4): colour

我知道这与向量的长度有关,但到目前为止,我完全不知道如何解决这个小问题。

geom_point() 需要 colour,而不是 fill。并且,将数据传递到 ggplot(data = ..) 后,无需再将其传递到 geom_point()

我还修复了在您的示例中创建 df 的错误。

rawdata<-data.frame(matrix(c(1,1,1,2,1,-1,3,-1,-1,4,-1,1,4,-2,2),5,3,byrow=TRUE))
names(rawdata)<-c("Town","x.coordinate","y.coordinate")
rawdata[,1]<-as.factor(rawdata[,1])


library(ggplot2)

ggplot(data=rawdata,aes(x=x.coordinate,y=y.coordinate,colour=Town)) + 
    geom_point()