1

I have a data frame that looks like this:

  Name        F        R        L         M
1    1 564.4745 3.267577 3.056806  878.4101
2    2 593.6801 4.848597 2.507691 1450.8099
3    3 117.3233 6.819547 2.673681 1151.8267
4  Avg 776.4827 4.878574 2.746059 1160.6822

And I want a stacked bar chart of all variables (F,R,L,M) for each observation (1,2,3,avg) but so far I can only set up individual bars in one chart. Help, please

ggplot(Test.tibble, aes(x = Name, y = F, fill = Name)) + 
geom_bar(stat = "identity") +
xlab("Name") +
ylab("Total") +
guides(fill = FALSE) +
theme_bw()

David N.F.
  • 35
  • 4
  • Please provide a reproducible example. Have a look [here](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). – Paul van Oppen Jun 08 '20 at 23:56
  • You also want your data to be in the long format. – statstew Jun 09 '20 at 00:04
  • 1
    Please do not post an image of code/data/errors: it cannot be copied or searched (SEO), it breaks screen-readers, and it may not fit well on some mobile devices. Ref: https://meta.stackoverflow.com/a/285557 (and https://xkcd.com/2116/). Please just include the code, console output, or data (e.g., `dput(head(x))` or `data.frame(...)`) directly. – r2evans Jun 09 '20 at 00:16

2 Answers2

2

Here is an approach with pivot_longer from tidyr:

library(dplyr)
library(tidyr)
library(ggplot2)
data %>% 
  pivot_longer(-Name, names_to = "Variable", values_to = "Value") %>%
ggplot(aes(x=Name, y = Value, fill = Variable)) +
  geom_bar(position = "stack", stat="identity")

enter image description here

Obviously the magnitude of R and L are much smaller than F and M, so they are very hard to see.

Ian Campbell
  • 23,484
  • 14
  • 36
  • 57
1

In base R, we can use barplot

barplot(`colnames<-`(t(df1[-1]), df1[[1]]), legend = TRUE, 
      col = c('blue', 'green', 'red', 'yellow'))

data

df1 <- structure(list(Name = c("1", "2", "3", "Avg"), F = c(564.4745, 
593.6801, 117.3233, 776.4827), R = c(3.267577, 4.848597, 6.819547, 
4.878574), L = c(3.056806, 2.507691, 2.673681, 2.746059), M = c(878.4101, 
1450.8099, 1151.8267, 1160.6822)), class = "data.frame", row.names = c("1", 
"2", "3", "4"))
akrun
  • 874,273
  • 37
  • 540
  • 662