MrASquare
MrASquare

Reputation: 139

Stacked bar plot with ggplot2

I have an R data frame of this form: (first, second, ... are row names; A, B, ... are col names)

              A   B   C    D  E
 first        30  0   0    0  0
 second       0   20  120  0  0
 third        0   40  100  0  0
 fourth       0   0   0    30 60

What I want ggplot() to do is plot a bar graph with the row names on the x axis and row sums on the y axis and those row sums should be color-stacked by the column head categories and be with number labels, so like this for the above data:

enter image description here

Upvotes: 0

Views: 1034

Answers (2)

AlexB
AlexB

Reputation: 3269

I think you are looking for something like this:

df %>%
  rownames_to_column(var = 'x') %>%
  pivot_longer(-x) %>%
  filter(value > 0) %>% 
  mutate(x = factor(x, levels = c('first', 'second', 'third', 'forth'))) %>% 
  ggplot(aes(fill = forcats::fct_rev(name), y = value, x = x, label = value)) +
  geom_bar(position="stack", stat="identity") +
  geom_text(aes(label=value)) +
  theme(legend.title = element_blank())

enter image description here

data:

structure(list(A = c(30L, 0L, 0L, 0L), B = c(0L, 20L, 40L, 0L
), C = c(0L, 120L, 100L, 0L), D = c(0L, 0L, 0L, 30L), E = c(0L, 
0L, 0L, 60L)), class = "data.frame", row.names = c("first", "second", 
"third", "forth")) -> df

Upvotes: 1

matfra
matfra

Reputation: 26

You should add rownames as a variable in your data frame, and transform your data to long format so ggplot can handle it. Something like this is close to what you mean I think:

yourDataFrame %>% 
    mutate(Label = rownames(df)) %>% # add row names as a variable
    reshape2::melt(.) %>% # melt to long format
    ggplot(., aes(x = Label, y = value, fill = variable)) + 
        geom_bar(stat='identity')

Upvotes: 1

Related Questions