使用ggplot2将R中的值居中

使用ggplot2将R中的值居中,r,graphics,plot,ggplot2,R,Graphics,Plot,Ggplot2,我正试图将这个答案应用到我的数据集中,但作为一个初学者,它根本不适合我 以下是示例集和示例代码: 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,re

我正试图将这个答案应用到我的数据集中,但作为一个初学者,它根本不适合我

以下是示例集和示例代码:

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)

d您需要为标签创建一个辅助数据框。我还重新构造了绘图代码,因为您希望最终对其进行更多操作,
qplot
实际上只适用于“快速”绘图或来自需要快速绘图的基本绘图:

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

请注意,您应该尽量避免将对象命名为与现有函数相同的东西(
t
是转置函数)。@nrussell感谢您的提醒。我编辑了我的示例代码。
table
也是一个现有的函数名。也不需要使用
png/dev.off()
作为示例;它只是创建了一个额外的步骤来打开文件以查看它的外观。另外,大多数人在保存
ggplot
对象时更喜欢使用
ggsave()
。@MrFlick谢谢,已编辑。。
gg <- gg + geom_text(data=d_labs, aes(x=Var1, label=Freq, y=Freq/2), size=3)