Chart of columns stacked in the R

4

I have a database where variables assume integers from 1 to 5.

Here is an example base with the variables X1 , X2 and X3 :

base<- rbind(
c(5,3,3),c(4,3,2),c(4,5,4),c(1,5,1),c(1,2,1),c(3,4,2),
c(2,3,2),c(3,1,3),c(3,2,4),c(5,1,5),c(3,4,5),c(5,4,4),
c(2,3,3),c(1,2,3),c(3,4,2),c(1,5,1),c(1,3,2),c(3,4,3),
c(4,2,3),c(4,2,3),c(1,3,3),c(1,3,4),c(1,2,2))  
base = data.frame(base)

Please how to make a column chart stacked with the occurrence frequencies of these values? That is, it would be a graph with three columns (X1, X2, X3) and each column would have 5 divisions proportional to the frequency of each of these values.     

asked by anonymous 23.03.2017 / 23:55

2 answers

3

If you reformat your database it is easy to do with ggplot2 . To reformat I am going to use reshape2 and dplyr :

library(ggplot2)
library(dplyr)
library(reshape2)
molten <- melt(base, variable.name = "variavel", value.name = "valores")
df <- molten %>% 
  group_by(variavel, valores = factor(valores)) %>% 
  summarise(frequencia = n())

ggplot(df, aes(x = variavel, y = frequencia, fill = valores)) +
  geom_bar(stat = "identity")

    
24.03.2017 / 03:39
3

Since ggplot2 2.2.0 there is also geom_col() which is a shortcut to geom_bar(stat = "identity") .

In this case, the syntax for the graph using the df of @Cinelli would be:

ggplot(df, aes(x = variavel, y = frequencia, fill = valores)) +
  geom_col()
    
24.03.2017 / 12:50