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.