Extend displaying values of bar plot to multivaria

2019-09-04 11:32发布

问题:

This question already has an answer here:

  • Showing data values on stacked bar chart in ggplot2 2 answers

I have been told that it is better to split up sub questions into multiple topics on SE, so here I go.

I have adapted the answer in this question to be presentable in a multivariate stacked bar plot. Everything works fine, however the values are not displaying correctly.

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)

But as you can see I am not sure how to merge ddply and melt (as provided in this answer). How should I go about this?

回答1:

I think something was lost in translation between the answer you linked to and your adaptation of it.

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