R 如何在ggplot中将x轴拆分为多个绘图?

R 如何在ggplot中将x轴拆分为多个绘图?,r,ggplot2,R,Ggplot2,我有以下数据集: df <- as.data.frame(cbind(Position = c(1,2,3,4,5,6,7,8,9,10), Value = c(11.31, 10.39, 9.50, 6.61, 5.41, 3.88, 3.81, 1.25, 0.70,10.41))) df这就是你要找的吗 df <- transform(df, Position=as.factor(Position), group=as.factor(findInt

我有以下数据集:

df <- as.data.frame(cbind(Position = c(1,2,3,4,5,6,7,8,9,10), 
    Value = c(11.31, 10.39, 9.50, 6.61, 5.41, 
    3.88, 3.81, 1.25, 0.70,10.41)))

df这就是你要找的吗

df <- transform(df, Position=as.factor(Position),
    group=as.factor(findInterval(Position, c(1, 4, 7, 10))))

ggplot(df, aes(x=Position, y=Value, fill=Position)) + 
    geom_bar(stat='identity') + 
    facet_grid(group ~ .)

df您可能希望使用package CAR的重新编码功能来定义自定义间隔,如下所示:

require(car)
require(ggplot2)
df['series']<-recode(df$Position, "1:3='1-3';4:6='4-6';7:9='7-9';10='10'")
ggplot(df, aes(x=Position, y=Value))+geom_bar(stat='identity')+facet_grid(~series)
require(汽车)
需要(ggplot2)

df['series']最简单的方法是使用
facet\u grid()

或者,为了更好地控制,您可以尝试创建单独的绘图&使用
gridExtra
package组合它们。

#数据

输入df感谢agenis,但我希望避免出现空位置。有可能吗?谢谢Matthew,我显然没有解释清楚。我想避免在每个方面都有空的位置。@blJOg,您可以将上面的代码调整为
facet\u网格(.~group,scales=“free”)
facet\u网格(.~group,scales=“free”)
几乎可以工作,但是facet 4有一个非常宽的条。@blJOg facet\u网格(.~group,scales=“free”,space=“free”)将允许每个方面的空间也发生变化。请尝试
facet\u网格(cols=vars(group),scales=“free\u x”,space=“free\u x”,drop=T)
ggplot(df, aes(x=Position, y=Value))+
    geom_bar(stat='identity')+
    facet_grid(~group,scales='free')
#Data
enter df <- as.data.frame(cbind(Position = c(1,2,3,4,5,6,7,8,9,10), 
                      Value = c(11.31, 10.39, 9.50, 6.61, 5.41, 
                                3.88, 3.81, 1.25, 0.70,10.41)))
#Grouping
df$group<-cut(df$Position,breaks=c(0,3,6,9,100),c('0-3','4-6','7-9','10'))

#Creating Individual Plots
p1=ggplot(subset(df,df$group=='0-3'), aes(x=Position, y=Value))+
    geom_bar(stat='identity')+
    ggtitle('0-3')

p2=ggplot(subset(df,df$group=='4-6'), aes(x=Position, y=Value))+
  geom_bar(stat='identity')+
  ggtitle('4-6')

p3=ggplot(subset(df,df$group=='7-9'), aes(x=Position, y=Value))+
  geom_bar(stat='identity')+
  ggtitle('7-9')

p4=ggplot(subset(df,df$group=='10'), aes(x=factor(Position), y=Value,width=Value/10))+
  geom_bar(stat='identity',width=0.7)+
  ggtitle('10')+
  xlab(label='Position')

grid.arrange(p1,p2,p3,p4,ncol=2,nrow=2,main='Plot')