我有以下数据集:
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)))
Run Code Online (Sandbox Code Playgroud)
我想把它绘制成一个条形图,其中位置值为1-3,4-6,7-9,10,在不同的图中,即彼此之下的4个单独的图.在ggplot中有一个简单的方法吗?
编辑:我想实现这一点,没有空位置.
干杯,约瑟夫
最简单的方法是使用facet_grid():

ggplot(df, aes(x=Position, y=Value))+
geom_bar(stat='identity')+
facet_grid(~group,scales='free')
Run Code Online (Sandbox Code Playgroud)
或者,为了获得更多控制,您可以尝试创建单独的图并使用gridExtra包来组合它们.

#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')
Run Code Online (Sandbox Code Playgroud)
这是您要找的吗?
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 ~ .)
Run Code Online (Sandbox Code Playgroud)

| 归档时间: |
|
| 查看次数: |
9092 次 |
| 最近记录: |