2

I've been searching to find a solution, but none of the already existing questions fit my problem.

I have a data.frame:

Pat <- c(1,1,1,1,1,1,2,2,2,2,2,2)
V_ID <- c(1,1,6,6,9,9,1,1,6,6,9,9)
T_ID <- c("A","B","A","B","A","B","A","B","A","B", "A","B")
apples <- c(1,1,1,1,1,1,1,1,1,1,1,1)
bananas <- c(2,2,2,2,2,2,2,2,2,2,2,2)
cranberries <- c(3,3,3,3,3,3,3,3,3,3,3,3)

df <- data.frame(Pat,V_ID, T_ID, apples, bananas, cranberries)

I am trying to plot:

barplot(as.matrix(df[,4:6]) ,
    main="tobefound", horiz = FALSE,width = 1, 
    names.arg=colnames(df[,4:6]),
    las=2,
    col = c("blue", "red"),
    legend = df[,3],
    args.legend = list(x="topleft"),
    beside= FALSE)

BARPLOT

enter image description here

I need two changes: First of all I like to have all "B"s (so the red part in every stack) piled up together and then the blue ones on top. Second: is there a way of decreasing the legend to only A and B once besides addressing this via

legend = df[1:2,3],

I am also looking for a solution using plotly or ggplot.

Thanks,

d.b
  • 32,245
  • 6
  • 36
  • 77
Rivka
  • 307
  • 1
  • 5
  • 19
  • Is [this](http://stackoverflow.com/questions/20349929/stacked-bar-plot-in-r?rq=1) what you're looking for? – iled Feb 20 '17 at 08:47
  • nope. Looked at your suggestion before. My goal is to have all "A"s and "B"s piled up together by colour. – Rivka Feb 20 '17 at 08:53

2 Answers2

3

First reshape:

df_long <- tidyr::gather(df, 'key', 'value', apples:cranberries) 

Then plot:

ggplot(df_long, aes(key, value, fill = T_ID)) + geom_col(col = 'black')

enter image description here

Or perhaps without the borders:

ggplot(df_long, aes(key, value, fill = T_ID)) + geom_col()

enter image description here

Axeman
  • 32,068
  • 8
  • 81
  • 94
3

Using base graphics, you needed to sort df by T_ID first.

df = df[order(df$T_ID), ]

barplot(as.matrix(df[,4:6]) ,
        main="tobefound", horiz = FALSE,width = 1, 
        names.arg=colnames(df[,4:6]),
        las=2,
        ylim = c(0,40),
        col = 1+as.numeric(as.factor(df$T_ID)),
        border = NA,
        beside= FALSE)

box()
legend('topleft', fill = 1+as.numeric(as.factor(levels(df$T_ID))), legend = levels(as.factor(df$T_ID)))

enter image description here

d.b
  • 32,245
  • 6
  • 36
  • 77