Iskandar The Pupsi
Iskandar The Pupsi

Reputation: 323

Displaying a stacked bar plot with a condition

I have this dataframe with numbers being percentages:

`df <- data.frame(spoken = c(10, 90, 30, 70), 
 lexicon = c(10, 90, 50, 50), 
 row.names = c("consonant_initial", 
    "vowel_initial", 
    "consonant_final",  "vowel_final"))`

I want to display that in a nice way so that I get a stacked barplot for the distribution of vowel vs consonant initial words and the distribution of vowel vs consonant final words, including facet_wrap to show the two conditions lexicon vs. spoken.

I have tried to reshape the data:

df$row <- seq_len(nrow(df)) df <- melt(df, id.vars = "row")

However, I can't wrap my head around how I would need to reshape the data in order to display it accordingly

Upvotes: 0

Views: 660

Answers (2)

jas_hughes
jas_hughes

Reputation: 56

You need to split the row names since the information you need to color code the stacked bars is encoded within, if I understand your desired graph correctly.

library(tidyverse)
df$label <- row.names(df)


df %>%
  separate(label, c("lettertype", "position"), "_") %>%
  gather(key = 'condition', value = 'prop', -lettertype, -position) %>%
  ggplot() +
  aes(x = position, y = prop, fill = lettertype) +
  geom_bar(stat = 'identity') +
  facet_wrap(~condition) 

enter image description here

Upvotes: 2

d.b
d.b

Reputation: 32548

df$row1 <- sapply(strsplit(row.names(df), "_"), function(x) x[1])
df$row2 <- sapply(strsplit(row.names(df), "_"), function(x) x[2])
library(reshape2)
df <- melt(df, id.vars = c("row1", "row2"))

library(ggplot2)
ggplot(df, aes(x = row2, y = value, fill = row1)) +
    geom_col() +
    facet_wrap(~variable)

enter image description here

Upvotes: 0

Related Questions