我有一个数据框列“ location”,它是一个具有8个级别(“ site01”,“ site02”,“ site03”,“ site04” .....“ site08”)的因子,每个级别都有一个纬度和经度作为数据框中的其他两列。
我需要做一个小平面网格并根据站点的纬度对站点进行排序。
我尝试订购该列,但它对ggplot2生成的图没有任何影响。
library(scales)
library(ggplot2)
sp <- ggplot(df, aes(x=year, y=value, col=coralType)) + geom_point(stat="identity") + facet_grid(location ~ coralType) +
theme(strip.text.x = element_text(size=8),
strip.text.y = element_text(size=8, face="bold", angle = 0),
strip.background = element_rect(colour="red", fill="#CCCCFF")) +
scale_x_continuous(name="Year", breaks=c(2010, 2013, 2016)) +
scale_y_continuous(name="Bleaching Percentage", breaks=seq(0,1,0.5), labels=percent)+
geom_smooth(method="lm")
sp
这会生成图,但不会根据站点的纬度对其进行排序。
答案 0 :(得分:0)
@ saksham-nagpal,在没有minimum reproducible example的情况下,我创建了一些虚拟数据并将其绘制。让我知道这个是否奏效。
# create some dummy data
corals<- c("red","blue","green")
df<- data.frame(siteLoc=paste0(("siteLoc"),1:6,rep("",6)),
lat=runif(6), long=c(-2, -1, 0, 1, 2, 5),
coralType = rep(corals,6)
)
df$mc <- cut(df$long, c(-Inf, 0, 1, Inf), c('level 1', 'level 2', 'level 3'))
# plot the data
library(ggplot2)
plt <- ggplot(df, aes(lat,long, colour = mc)) + geom_point(stat="identity")
plt + facet_grid(coralType ~ mc, scales="free")
sp<-plt + facet_grid(coralType ~ mc, scales="free_y")+
theme(strip.text.x = element_text(size=8),
strip.text.y = element_text(size=8, face="bold", angle = 0),
strip.background = element_rect(colour="red", fill="#CCCCFF"))+
scale_x_continuous(name="Year", breaks=c(2010, 2013, 2016)) +
scale_y_continuous(name="Bleaching Percentage", breaks=seq(0,1,0.5))+
geom_smooth(method="lm")
sp
现在,如果您查看变量coralType
的级别,例如levels(df$coralType)
。它将显示为[1] "blue" "green" "red"
。假设您希望像[1] "red" "blue" "green"
这样重新排列级别。在这种情况下,您需要将因子水平重新排序为
# reorder the factors
df$reordrFactor<- factor(df$coralType, levels = c("red","blue","green"))
levels(df$reordrFactor)
[1] "red" "blue" "green"
现在,如果将其绘制出来,将获得所需的结果。
# plot according to reordered factor levels
plt <- ggplot(df, aes(lat,long, colour = mc)) + geom_point(stat="identity")
plt + facet_grid(reordrFactor ~ mc, scales="free")
sp<-plt + facet_grid(reordrFactor ~ mc, scales="free_y")+
theme(strip.text.x = element_text(size=8),
strip.text.y = element_text(size=8, face="bold", angle = 0),
strip.background = element_rect(colour="red", fill="#CCCCFF"))+
scale_x_continuous(name="Year", breaks=c(2010, 2013, 2016)) +
scale_y_continuous(name="Bleaching Percentage", breaks=seq(0,1,0.5))+
geom_smooth(method="lm")
sp
希望这会有所帮助。