bargraph in ggplot with different numbers of bars

2019-07-11 18:44发布

问题:

My dataset looks like this:

`DSET<-data.frame(cbind(c(rep("V1",3),rep("V2",3),"V3"),
                       c(rep(c("X1","X2","X3"),2),"X1"),
                       c(rep(1,7))))`    
`names(DSET)<-c("A","B","C")`    
`DSET[,3]<-c(1,-2,1,3,-1,2,-3)` 

With three grouping variables (V1,V2,V3) and three variables per Group (X1,X2,X3). The Problem is that group 3 (V3) has only one variable (X1) but lacks the two others. If I want to produce a bargraph, now, everything works fine despite the fact that the bar of group 3 is three times as large than the ones in group one and two.

`Grph<-ggplot(DSET,aes(x=A,y=C,fill=B))`    
`dodge <- position_dodge(width=0.9)`    
`Grph+geom_bar(position=dodge)` 

I tried to add two rows with the lacking groups and the value 0 for X2 and X3 and It works somewhat.

`DSET<-data.frame(cbind(c(rep("V1",3),rep("V2",3),rep("V3",3)),
                       c(rep(c("X1","X2","X3"),3)),c(rep(1,9))))`    
`names(DSET)<-c("A","B","C")`    
`DSET[,3]<-c(1,-2,1,3,-1,2,-3,0,0)` 

`Grph<- ggplot(DSET,aes(x=A,y=C,fill=B))`    
`dodge <- position_dodge(width=0.9)`    
`Grph+geom_bar(position=dodge)` 

But what I would really like to achieve is a plot that adjusts the group size depending on the number of bars each group has by keeping the bar width constant. Is there any way to do this?

looking forward to your help!

回答1:

If I understand your question correctly, you want the amount of space allocated to "V3" to be less than the space allocated to "V1" and "V2" since there is only one "X" in "V3", and you want the width of each bar representing an "X" to be the same? If so, you can get this using facets, but not with a simple x scale.

First, an easier way to create your two data frames (and giving them different names):

DSET <- data.frame(A=c(rep("V1",3),rep("V2",3),"V3"),
                   B=c(rep(c("X1","X2","X3"),2),"X1"),
                   C=c(1,-2,1,3,-1,2,-3))

DSET2 <- data.frame(A=rep(c("V1","V2","V3"), each=3),
                    B=rep(c("X1","X2","X3"), times=3),
                    C=c(1,-2,1,3,-1,2,-3,0,0))

Your two graphs:

Grph <- ggplot(DSET, aes(x=A, y=C, fill=B)) +
  geom_bar(position=position_dodge(width=0.9))
Grph

Grph %+% DSET2

To get like what you want using facets, use:

ggplot(DSET, aes(x=B, y=C, fill=B)) +
  geom_bar(position=position_dodge(width=0.9)) +
  facet_grid(.~A, scale="free_x", space="free")



标签: r ggplot2