Reputation: 11
I'm trying to create a stacked bar chart of for values that take place in time. I have a 5 observation dataframe that has 3 variables: anio, frac_exp and frac_nac. Year takes 5 values (2013, 2014, 2015, 2016 and 2017). frac_exp and frac_nac are percentages corresponding to each category on each year. For example, a row on my dataframe could look like: 2013 0.31 0.69; this would mean on 2013 31% of the total corresponded to frac_exp and 69% to frac_nac. I want to do a stacked bar chart, using ggplot2, showing the proportions corresponding to each category every year but I cannot seem to do it. Could anyone help me?
Upvotes: 1
Views: 42
Reputation: 38
For this, I believe a longer format is necessary for your dataframe.
# Create OP's original dataframe:
year <- as.factor(2013:2017)
frac_exp <- runif(5, min = 0.05, max = 0.95)
frac_nac <- 1-frac_exp
df <- data.frame(year, frac_exp, frac_nac)
# Simple way of melting it into longer format:
# For a function that melts dataframe, check out melt() from package reshape2.
df2 <- data.frame(year = rep(year, 2),
type = rep(c("exp", "nac"), each = nrow(df)),
frac = c(df$frac_exp, df$frac_nac)
)
# Now it is easy to make a nice stacked barplot in ggplot:
ggplot(data = df2, mapping = aes(x = year, y = frac, fill = type))+
geom_col()
Upvotes: 0