在 ggplot2 中使用 facet_grid 更改中断数
Change the number of breaks using facet_grid in ggplot2
我有这样一种数据:
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() 与 scales="free_x" 选项一起使用时,我获得了 5 个具有不同中断次数的图表。 5张图有可能有相同的断点数吗?例如 3.
ggplot(a, aes(x, y))+geom_point()+ facet_grid(~group, scales="free_x")
我知道,如果我删除 scales="free_x" 选项,我将获得 5 个图表的相同比例,但情节变得如此丑陋。你能帮帮我吗?
您可以定义自己喜欢的休息功能。在下面的示例中,我显示了等距间隔。请注意,函数中的 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'))
我有这样一种数据:
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() 与 scales="free_x" 选项一起使用时,我获得了 5 个具有不同中断次数的图表。 5张图有可能有相同的断点数吗?例如 3.
ggplot(a, aes(x, y))+geom_point()+ facet_grid(~group, scales="free_x")
我知道,如果我删除 scales="free_x" 选项,我将获得 5 个图表的相同比例,但情节变得如此丑陋。你能帮帮我吗?
您可以定义自己喜欢的休息功能。在下面的示例中,我显示了等距间隔。请注意,函数中的 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'))