简体   繁体   English

在ggplot2中使用facet_grid更改中断的数量

[英]Change the number of breaks using facet_grid in ggplot2

I have a kind of data such as: 我有一种数据,如:

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)

and when I use facet_grid() with scales="free_x" option I obtain 5 graphs with different number of breaks. 当我使用带有scales =“free_x”选项的facet_grid()时,我获得了5个具有不同休息次数的图形。 It is possible that the 5 graphs have the same number of breaks? 5个图表可能具有相同的中断次数? For example 3. 例如3。

ggplot(a, aes(x, y))+geom_point()+ facet_grid(~group, scales="free_x")

I know that if I remove the scales="free_x" option I obtain the same scale for the 5 graphs, but the plot it turns so ugly. 我知道如果我删除了scales =“free_x”选项,我会获得5个图形的相同比例,但是它变得如此丑陋。 Can you help me? 你能帮助我吗?

You can define your own favorite breaks function. 您可以定义自己喜欢的休息功能。 In the example below, I show equally spaced breaks. 在下面的示例中,我显示了等距间隔。 Note that the x in the function has a range that is already expanded by the expand argument to scale_x_continuous . 请注意,函数中的x具有已通过expand参数expandscale_x_continuous In this case, I scaled it back (for the multiplicative expand argument). 在这种情况下,我缩放它(对于乘法扩展参数)。

# 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'))

结果图像

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM