My dataset:
Taxa dn dc
Cha 10.2 -20.4
Cha 10.7 -19.7
Cha 4.9 -21.0
Cha 5.4 -20.6
Cha 8.6 -21.2
Cha 8.0 -20.9
Cha 8.1 -21.3
Cha 6.9 -21.1
Cha 8.5 -21.1
Cha 9.1 -20.8
Hyd 6.6 -19.2
Hyd 10.2 -17.0
Hyd 9.7 -18.2
Hyd 8.1 -16.5
Hyd 8.8 -15.8
Hyd 8.7 -15.8
Hyd 7.6 -18.3
Hyd 8.9 -16.0
Hyd 8.4 -17.5
Hyd 9.8 -18.8
Hyd 8.3 -18.4
Scy 9.4 -20.1
Scy 9.1 -20.0
Scy 7.8 -20.2
Scy 9.1 -17.6
Scy 8.2 -19.8
Scy 9.4 -19.2
Scy 9.0 -20.1
Sip 5.7 -15.2
Sip 6.2 -18.6
Sip 5.6 -18.0
Sip 8.6 -17.6
Sip 4.8 -16.9
Sip 5.2 -15.4
Sip 1.9 -18.4
The code I use is:
library(ggplot2)
ggplot(mydata, aes(x=dC, y=dN, colour=Taxa, shape=Taxa))+
geom_point(size=2, alpha=0.5)+
geom_polygon(aes(fill=Taxa, group=Taxa))+
theme(legend.position = "none")
I would like to plot the polygon group with "Taxa" in my data. However, it looks like the polygon connects each point.
What I want is like this one. How should I edit my codes?
To connect outer points in group and encircle ones that are within the group use geom_encircle
function from ggalt
package.
library(ggplot2)
library(ggalt)
ggplot(mydata, aes(dc, dn)) +
geom_point(aes(color = Taxa)) +
geom_encircle(aes(fill = Taxa), s_shape = 1, expand = 0,
alpha = 0.2, color = "black", show.legend = FALSE)
Use s_shape = 1
and expand = 0
to connect outer points, otherwise it will encircle with margins.
You can also calculate the convex hulls, them plot them down:
library(ggplot2)
library(plyr)
# some fake data:
mydata <- data.frame(Taxa = c('Cha','Cha','Cha','Cha','Cha','Cha','Hyd','Hyd','Hyd','Hyd','Hyd','Hyd'),
dn = c(10.2,10.7,4.9,5.4,8.6,8.0, 6.6,10.2,9.7,8.1,8.8,8.7),
dc =c(-20.4,-19.7,-21.0,-20.6,-21.2,-20.9,-19.2,-17.0,-18.2,-16.5,-15.8,-15.8))
# calculate convex hulls:
chulls <- ddply(mydata, .(Taxa), function(mydata) mydata[chull(mydata$dn, mydata$dc), ])
# plot them:
ggplot(data=mydata, aes(x=dn, y=dc, color=Taxa)) + geom_point() +
geom_polygon(data=chulls, aes(x=dn, y=dc, fill=Taxa, alpha=0.2))
Nice source here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With