显示带有条件的堆积条形图

时间:2019-07-10 16:46:32

标签: r ggplot2 stacked-chart

我有这个数据框,数字是百分比:

`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"))`

我想以一种很好的方式显示它,以便 堆叠的条形图,用于分配元音与辅音初始单词 元音与辅音最终词的分布 包括facet_wrap来显示词典与口语的两个条件。

我试图重塑数据:

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

但是,我无法围绕需要如何整形数据以进行相应显示的问题

2 个答案:

答案 0 :(得分:2)

如果我正确理解了所需的图形,则需要对行名称进行拆分,因为对堆叠的条进行颜色编码所需的信息已编码在其中。

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

答案 1 :(得分:0)

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

相关问题