我有一个数据框,其中数字是百分比:
`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")
但是,我无法理解需要如何对数据进行整形才能相应地显示数据
发布于 2019-07-11 01:04:12
您需要拆分行名,因为您需要对堆叠条形图进行颜色编码的信息是在其中编码的,如果我正确理解了您想要的图形。
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)

发布于 2019-07-11 00:57:45
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)

https://stackoverflow.com/questions/56975237
复制相似问题