Trouble producing a polygon on top of a scatterplo

2019-07-29 20:01发布

问题:

Currently, I am trying to transition my graphical knowledge from the plot function in R, to the ggplot function. I have began constructing scatterplots and corresponding legends for a given data set, however I want to incorporate the function geom_polygon onto my plots using ggplot.

Specifically, I want to capture a triangular region from the origin of a scatterplot. For reproducibility, say I have the following data set:

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

To construct a scatterplot along with a legend, I have been told to do the following:

p1<-ggplot(data=rawdata,aes(x=x.coordinate,y=y.coordinate,colour=Town,shape=Town)) 
+ theme_bw() + geom_point()  

The result is the following: Click here.

What I want to do now is produce a polygon. To do so, I have construct the following dataframe to use in the geom_polygon function:

geom_polygon(data=polygondata,aes(x = xa, y = ya),colour="darkslategray2",
             fill = "darkslategray2",alpha=0.25)

However, when I combine this with p1, I get the following error:

Error in eval(expr, envir, enclos) : object 'Town' not found

From some messing around, I have noticed that when I omit the shape argument from the ggplot function, I can easily produce the desired output which is shown here. However, I wish to keep the shape for aesthetics.

I also get a similar problem when I try to produce arrows which connect points on the scatterplot using ggplot. However, I will address this problem after, as the root problem may be here.

回答1:

Add the following to polygondata:

polygondata$Town = NA

Even though you're not using that variable in geom_polygon, ggplot expects it to be there if that column is used for an aesthetic in the main call to ggplot.

Alternatively, I think you could avoid the error if you move the aesthetic mapping in the initial plot to geom_point rather than the main ggplot call, like this:

p1 <- ggplot(data=rawdata) + 
        theme_bw() + 
        geom_point(aes(x=x.coordinate, y=y.coordinate, colour=Town, shape=Town)) 

In that case, you wouldn't need to add a Town column to polygondata.