ggplot2 facet_grid组变量

时间:2014-01-03 10:39:44

标签: r ggplot2 facet-grid

我正在使用以下代码创建facet_grid图:

load(url("http://ebib.com.br/dados.RData"))

library(ggplot2)
library(scales)

ggplot() + geom_step(data=subset(me, variable=="Umid. Relat."), aes(Data, value), color="blue") +
   geom_smooth(data=subset(me, variable=="Umid. Relat."), aes(Data, value), , color="blue") +
   geom_line(data=subset(me, variable=="Vel. Vento"), aes(Data, value), color="gray20") +
   geom_smooth(data=subset(me, variable=="Vel. Vento"), aes(Data, value), color="gray20") +
   geom_line(data=subset(me, variable==c("Temp. Max.", "Temp. Min.")), aes(Data, value, colour=variable)) +
   geom_smooth(data=subset(me, variable==c("Temp. Max.", "Temp. Min.")), aes(Data, value, colour=variable)) +
   geom_bar(stat="identity", data=subset(me, variable=="Precipitação"), aes(Data, value), fill="blue") +
   facet_grid(variable~., scales="free_y") +
   scale_x_date(breaks = date_breaks("months"), labels = date_format("%b")) +
   theme(legend.position="none")

有没有办法绘制变量“Temp.Max。”和“Temp.Min。”在同一图/方面?

修改:工作代码

load(url("http://ebib.com.br/dados.RData"))

library(ggplot2)
library(scales)

me$variable2 <- as.character(me$variable)
me$variable2[me$variable2 %in% c("Temp. Max.","Temp. Min.")] <- "Temp. Max./Min."

ggplot() + geom_line(data=subset(me, variable=="Umid. Relat."), aes(Data, value), color="blue") +
geom_smooth(data=subset(me, variable=="Umid. Relat."), aes(Data, value), , color="blue") +
geom_line(data=subset(me, variable=="Vel. Vento"), aes(Data, value), color="gray20") +
geom_smooth(data=subset(me, variable=="Vel. Vento"), aes(Data, value), color="gray20") +
geom_line(data=subset(me, variable==c("Temp. Max.", "Temp. Min.")), aes(Data, value, colour=variable)) +
geom_smooth(data=subset(me, variable==c("Temp. Max.", "Temp. Min.")), aes(Data, value, colour=variable)) +
geom_bar(stat="identity", data=subset(me, variable=="Precipitação"), aes(Data, value), fill="blue") +
facet_grid(variable2~., scales="free_y") +
scale_x_date(breaks = date_breaks("months"), labels = date_format("%b")) +
theme(legend.position="none")

1 个答案:

答案 0 :(得分:3)

你需要一个新的变量来进行分面。

新列variable2几乎与variable相同,但"Temp. Max./Min.""Temp. Max."都有一个值"Temp. Min."

me$variable2 <- as.character(me$variable)
me$variable2[me$variable2 %in% c("Temp. Max.","Temp. Min.")] <- "Temp. Max./Min."

将此变量用作facet_grid的参数:

facet_grid(variable2 ~., scales = "free_y")

这将产生以下情节:

enter image description here