0

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

1
  • What do you mean 'colour stacked'? Commented Aug 13, 2021 at 15:41

2 Answers 2

1

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')
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.