我有一种数据,例如:
y<-rep(c(1, 2, 3), times=5)
group<-rep(c("a", "b", "c", "d", "e"), each=3)
x<-c(2, 3, 4, 5, 7, 10, 10, 15, 19, 8, 10, 14, 25, 28, 33)
a<-data.frame (x, y, group)
当我使用facet_grid()时,scale =&#34; free_x&#34;选项我获得5个具有不同休息次数的图表。 5个图表可能具有相同的中断次数?例如3。
ggplot(a, aes(x, y))+geom_point()+ facet_grid(~group, scales="free_x")
我知道如果我删除了scale =&#34; free_x&#34;选项我获得了5个图形的相同比例,但它变得如此丑陋。你能救我吗?
答案 0 :(得分:9)
您可以定义自己喜欢的休息功能。在下面的示例中,我显示了等距间隔。请注意,函数中的x
的范围已经由expand
参数扩展到scale_x_continuous
。在这种情况下,我缩放它(对于乘法扩展参数)。
# loading required packages
require(ggplot2)
require(grid)
# defining the breaks function,
# s is the scaling factor (cf. multiplicative expand)
equal_breaks <- function(n = 3, s = 0.05, ...){
function(x){
# rescaling
d <- s * diff(range(x)) / (1+2*s)
seq(min(x)+d, max(x)-d, length=n)
}
}
# plotting command
p <- ggplot(a, aes(x, y)) +
geom_point() +
facet_grid(~group, scales="free_x") +
# use 3 breaks,
# use same s as first expand argument,
# second expand argument should be 0
scale_x_continuous(breaks=equal_breaks(n=3, s=0.05),
expand = c(0.05, 0)) +
# set the panel margin such that the
# axis text does not overlap
theme(axis.text.x = element_text(angle=45),
panel.margin = unit(1, 'lines'))