在ggplot()的小节顶部添加星号时出错

时间:2019-05-06 18:10:30

标签: r ggplot2

我想在小节图的顶部添加一个星星以说明统计意义。

我正在使用以下脚本。但是,尽管我在另一篇文章中使用了完全相同的代码,但我仍然收到错误消息:


> gg <- ggplot(aes(x=category, y=mean, fill=split, group=split), data=data)
> gg <- gg + geom_bar(stat='identity', position = position_dodge(), width=.5)
> gg <- gg + geom_errorbar(aes(ymin=mean-sd, ymax=mean+sd), position = position_dodge(width=.5), width=.2)
> gg <- gg +  scale_x_discrete(labels=c("Accuracy", "Precision", "Recall"))
> gg <- gg + xlab("Precision metrics") + ylab("Mean") + labs (fill="Classifier") + scale_fill_discrete(labels = c("k-NN", "Decision trees"))
> gg <- gg + theme(legend.position = "none") 
> 
> 
> label.df <- data.frame(Group = c("Accuracy"),
+                        Value = c(0.99))
> 
> gg + geom_text(data = label.df, label = "**")
Don't know how to automatically pick scale for object of type function. Defaulting to continuous.
Error in FUN(X[[i]], ...) : object 'category' not found

这是情节。我想在Accuracy红色条的顶部添加星星。 the plot

感谢任何输入!

PS:我在下面提供了一个dput()示例:

> dput(data)
structure(list(mean = c(0.9685, 0.925333333333333, 0.985666666666667, 
0.926833333333333, 0.968666666666667, 0.931333333333333), sd = c(0.0150831031289984, 
0.0301838809079725, 0.013306639946533, 0.0589488478824367, 0.0147873820085459, 
0.0712338870669478), category = structure(c(1L, 1L, 2L, 2L, 3L, 
3L), .Label = c("1", "2", "3"), class = "factor"), split = structure(c(1L, 
2L, 1L, 2L, 1L, 2L), .Label = c("1", "2"), class = "factor")), row.names = c("a", 
"c", "e", "g", "i", "k"), class = "data.frame")

1 个答案:

答案 0 :(得分:0)

您可以尝试annotate。此外,建议使用geom_col代替geom_bar

 ggplot(df, aes(x=category, y=mean, fill=split)) +
   geom_col(position = position_dodge(width = 0.9)) + 
   geom_errorbar(aes(ymin=mean-sd, ymax=mean+sd), position = position_dodge(width=.9), width = .2) +
   scale_x_discrete(labels=c("Accuracy", "Precision", "Recall")) +
   theme(legend.position = "none") +
   annotate("text", x = 1, y = 1, label = "**") 

enter image description here