Halfway
Halfway

Reputation: 13

Stacked bar chart for each column

citetest<-data.frame(db=c("db1","db2","db3","db4","db5"), 
                     risall=c(248,134,360,122,46),
                     riscross=c(149,88,255,100,40),
                     risuniq=c(99,46,105,22,6))

head(citetest)
#>    db risall riscross risuniq
#> 1 db1    248      149      99
#> 2 db2    134       88      46
#> 3 db3    360      255     105
#> 4 db4    122      100      22
#> 5 db5     46       40       6

Created on 2022-07-29 by the reprex package (v2.0.1)

enter image description here

using the above dataframe I'm looking to develop a stacked bar chart, one for each "dbx" column. The fill colors need to align with the corresponding row.

ggplot(df, aes(x=db, y=y, fill=y))+
    geom_bar(position="stack", stat="identity")

Upvotes: 0

Views: 383

Answers (1)

harre
harre

Reputation: 7297

You need to get your phases-columns in a long format in order to plot them with ggplot:

library(tidyr)

citetest |> 
  pivot_longer(-db) |>
  ggplot(aes(x=db, y=value, fill=name))+
  geom_bar(position="stack", stat="identity")

enter image description here

Upvotes: 1

Related Questions