问题描述
我有一种数据,例如:
$ p $ y 组 x< -c(2 ,3,4,5,7,10,10,15,19,8,10,14,25,28,33)
a
当我使用facet_grid()和scales =free_x选项时,我获得5个不同数目的图的休息时间。这5个图表可能有相同的休息次数?例如3.
ggplot(a,aes(x,y))+ geom_point()+ facet_grid(〜group,scale =free_x)
我知道如果删除了scales =free_x选项, 5张图的规模相同,但情节变得如此丑陋。你可以帮我吗?
您可以定义您自己的最爱休息功能。在下面的例子中,我展示了等间隔的休息。请注意,函数中的 x
的范围已经被展开
参数扩展为 scale_x_continuous
。在这种情况下,我将其缩小(用于乘法扩展参数)。
#加载所需软件包
require(ggplot2)
require(grid)
#定义break函数,
#s是比例因子(参见乘法扩展)
equal_breaks< - 函数(n = 3,s = 0.05,...){
函数(x ){b $ b#rescaling
d seq(min(x)+ d,max(x) - (a,aes(x,y))+
geom_point()+ b
$
facet_grid(〜group,scales =free_x)+
#使用3个分隔符,
#使用与第一个扩展参数相同的s,
#second扩展参数应该是0
scale_x_continuous(breaks = equal_breaks(n = 3,s = 0.05),
expand = c(0.05,0))+
#设置面板边距,使
#轴文本不重叠
主题(axis.text.x = element_text(angle = 45),
panel.margin = unit(1,'lines'))
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. It is possible that the 5 graphs have the same number of breaks? For example 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. 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
. 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'))
这篇关于使用ggplot2中的facet_grid更改中断的数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!