我正在尝试为不同的方面设置不同的Y轴范围。我在网上看了很多答案,我试着将它们应用到我的脚本上,但似乎没有用。
我正在使用scales = "free"
让轴出现在所有方面,我使用geom_blank
根据Variable
的变量somePoints
设置不同的轴限制数据帧
以下是数据的可重现示例:
library(ggplot2)
dummy <- expand.grid(Year = NA, Season = c("Winter","Spring","Summer","Fall"),
Variable = c("P","T"), stringsAsFactors=FALSE)
dummy$ymin = NA
dummy$ymax = NA
dummy[dummy$Variable=="P","ymin"] = 0
dummy[dummy$Variable=="P","ymax"] = 400
dummy[dummy$Variable=="T","ymin"] = -10
dummy[dummy$Variable=="T","ymax"] = 30
somePoints = expand.grid(Year = NA, Season = c("Winter","Spring","Summer","Fall"),
Variable = c("P","T"), stringsAsFactors=FALSE)
somePoints$Value = NA
somePoints[somePoints$Variable=="P","Year"] = 1940
somePoints[somePoints$Variable=="T","Year"] = 1940
somePoints[somePoints$Variable=="P","Value"] = c(350,365,200,150)
somePoints[somePoints$Variable=="T","Value"] = c(-5,8,25,7)
基本上我想要的是P
变量的Y轴相同,范围从0到400,T
的Y轴相同,变量范围从-10到30。
以下是我用来获取我想要的ggplot
代码行:
ggplot()+
facet_grid(Season ~ Variable, scales = "free_y")+
geom_blank(data = dummy,aes(y=ymin)) +
geom_blank(data = dummy,aes(y=ymax)) +
geom_point(data = somePoints, aes(Year,Value), size = 5) +
geom_point(data = somePoints, aes(Year,Value), size = 5)
我注意到在scales = "free_y"
函数中设置facet_grid
似乎无效。
我做错了什么?我觉得我错过了一些愚蠢的东西。
谢谢。
答案 0 :(得分:0)
如果我理解正确,geom_blank
的问题更多。 geom_blank
的目的是确保不同情节之间的共同尺度。您应该使用expand
参数。我建议尝试以下方法:
library(ggplot2)
ggplot()+
facet_grid(Season ~ Variable, scales = "free_y")+
geom_point(data = somePoints, aes(Year,Value), size = 5) +
geom_point(data = somePoints, aes(Year,Value), size = 5) +
scale_y_continuous(expand = c(.2,0))
expand
只是缓冲你的边缘。
或者,您可以使用facet_wrap
而不是facet_grid
,以便在每个图上显示轴。我们只需指定列数(ncol = 2
)和垂直方向(vir = "v"
):
ggplot()+
facet_wrap(Variable ~ Season, scales = "free_y",
dir = "v", ncol = 2)+
geom_blank(data = dummy,aes(y=ymin)) +
geom_blank(data = dummy,aes(y=ymax)) +
geom_point(data = somePoints, aes(Year,Value), size = 5) +
geom_point(data = somePoints, aes(Year,Value), size = 5) +
scale_y_continuous(expand = c(.2,0))
如果您不喜欢这些标签,可以将labeller = labeller(.multi_line = FALSE)
传递给facet_grid