Rivka Rivka - 9 months ago 30
R Question

R: grouped bar plot every x rows

I have a dataframe like this:

S_ID <- c(1,1,1,1,1,1,1,1)
V_ID <- c(5,5,5,5,8,8,8,8)
T_ID <- c("A","A","B","B","A","A","B","B")
marker1 <- c("+","-","+", "-", "+", "-","+", "-")
marker2 <- c("-","-","-", "-", "-", "-","-", "-")
value <- c(1,2,3,4,5,6,7,8)

df <- data.frame(S_ID, V_ID,T_ID,marker1, marker2, value)


enter image description here

and I would like to plot a barchart from it. I tried different approaches but just can't get it right. Value should be on the y-axis. x- axis will be 16 labels from : "++++" to "----" coming from columns 4 to 7.
(in minimal example cut don to every 3)

enter image description here

I have different (usually 4) Tube IDs, so I would like all Tube IDs for "++++" grouped together. I am also adding axis with the axis function for the x-labels

My first approach was having 16 columns, but as I want to a present the table as well, this option is too confusing and long.

My solution so far includes a plot, that looks like this:

enter image description here

as you can see, I get the bars,(the x axis is not aligned well here) but I need the bars grouped and I don't know how to get my table grouped every 16 rows.

I am very thankful for any help!

Answer Source
library('ggplot2')
df1$grp <- factor( with(df1, paste( marker1, marker2, sep = '\n' ) ) )
ggplot(data = df1, mapping = aes( x = grp, y = value, color = T_ID, fill = T_ID)) +
  geom_bar( stat = 'identity', position =  position_dodge(width=0.55), width = 0.5) + 
  theme( axis.text.x = element_text( angle = 0 )) +
  xlab( label = 'Markers' ) + 
  ylab( label = 'Effect' )

enter image description here

Using interaction

ggplot(data = df1, mapping = aes( x = interaction(marker1, marker2), y = value, color = T_ID, fill = T_ID)) +
  geom_bar( stat = 'identity', position =  position_dodge(width=0.55), width = 0.5) + 
  theme( axis.text.x = element_text( angle = 0 )) +
  xlab( label = 'Markers' ) + 
  ylab( label = 'Effect' )

enter image description here

Data:

S_ID <- c(1,1,1,1,1,1,1,1)
V_ID <- c(5,5,5,5,8,8,8,8)
T_ID <- c("A","A","B","B","A","A","B","B")
marker1 <- c("+","-","+", "-", "+", "-","+", "-")
marker2 <- c("-","-","-", "-", "-", "-","-", "-")
value <- c(1,2,3,4,5,6,7,8)
df1 <- data.frame(S_ID, V_ID,T_ID,marker1, marker2, value)