显示带有条件的堆积条形图
Displaying a stacked bar plot with a condition
我有这个数据框,数字是百分比:
`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")
但是,我无法理解我需要如何重塑数据才能相应地显示它
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)
您需要拆分行名称,因为如果我正确理解您想要的图表,您需要对堆叠条形图进行颜色编码的信息已在其中编码。
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)
我有这个数据框,数字是百分比:
`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")
但是,我无法理解我需要如何重塑数据才能相应地显示它
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)
您需要拆分行名称,因为如果我正确理解您想要的图表,您需要对堆叠条形图进行颜色编码的信息已在其中编码。
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)