Centering values in R with ggplot2

2019-08-03 08:58发布

I am trying to apply this answer to my dataset, but - being a beginner, it isn't working out for me at all.

Here is a sample set and sample code:

d <- 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))

    qplot(factor(Variant), data=d, geom="bar", fill=Variant) +
      theme_bw() +
      xlab("") +
      ylab("Frequencies") + 
      geom_text(aes(label = factor(Variant), y = 5), size = 3)

This is a simple bar plot, of only two elements (so the bar plot should show the frequency of "iedere" and "elke"). I tried adding geom_text with a value that I thought would at least show the amount of occurences, but that doesn't work. Instead it shows me the labels, not the values.

I would also like to apply this to stacked plots and a grouped stacked plot - as shown here. I am assuming that the method is the same for all three graphs, but seeing that I can't even get the first one to work with the code provided, I didn't try the other two. Some directions and help would be greatly appreciated.

1条回答
孤傲高冷的网名
2楼-- · 2019-08-03 09:13

You'll need to create a secondary data frame for the labels. I also restructured the plotting code since you want to eventually do more with it and qplot is really just for "quick" plots or those coming from base plotting who need a quick mapping:

d_labs <- data.frame(table(d$Variant))

gg <- ggplot(d, aes(x=Variant))
gg <- gg + geom_bar(aes(fill=Variant))
gg <- gg + geom_text(data=d_labs, aes(x=Var1, label=Freq), y=5, size=3)
gg <- gg + theme_bw()
gg <- gg + labs(x=NULL, y="Frequencies")
gg

enter image description here

You get way more control over the geom_text geoms this way.

EDIT

You can map the vertical position to the Freq aesthetic:

gg <- gg + geom_text(data=d_labs, aes(x=Var1, label=Freq, y=Freq/2), size=3)

enter image description here

查看更多
登录 后发表回答