将条形图的显示值扩展到多变量堆叠条形

时间:2015-01-10 09:08:36

标签: r graphics ggplot2

我被告知最好将子问题分成SE上的多个主题,所以我在这里。

我已将the answer in this question改编为a multivariate stacked bar plot。一切正常,但值无法正确显示。

dnom <- data.frame(Variant = sample(c("iedere","elke"),size = 50,replace = TRUE),
        Region = sample(c("VL","NL"),size = 50,replace = TRUE),
        PrecededByPrep = sample(c("1","0"),size = 50,replace = TRUE),
        Person = sample(c("person","no person"),size = 50,replace = TRUE),
        Time = sample(c("time","no time"),size = 50,replace = TRUE))

ggplot.labs <- data.frame(table(dnom))
# OR?
ggplot.data <- melt(dnom, id.vars = "Variant")
ggplot.data <- ddply(ggplot.labs, .(Var1), transform, pos = cumsum(Freq) - (0.5 * Freq))

ggplot(dnom, aes(x=Variant)) +
        geom_bar(aes(fill=Variant)) + 
        geom_text(data=ggplot.labs, aes(x=Var1, label=Freq, y=Freq/2), size=3) +
        scale_fill_manual(values = c("paleturquoise3", "palegreen3")) +
        theme_corpling() +
        labs(x="Variant", y="Frequentie", title="Distributie van varianten") +
        guides(fill=FALSE)

但正如您所见,我不确定如何合并ddplymelt(如this answer中所述)。我应该怎么做呢?

1 个答案:

答案 0 :(得分:1)

我认为你所链接的答案与你的改编之间在翻译中丢失了一些东西。

# Code from an older edit of the question.
dnom_labs <- data.frame(table(dnom$Region, dnom$Variant))

# Suggested answer
Data <- ddply(dnom_labs, .(Var1), transform, pos = cumsum(Freq) - (0.5 * Freq))

ggplot(Data, aes(x=Var1, y = Freq)) +
        geom_bar(aes(fill=Var2), stat = "identity") + 
        geom_text(aes(label = Freq, y = pos), size = 3) +
        labs(x="Region", y="Frequencies", title="Distribution of variant")

enter image description here