例如,这段代码
data <- data.frame(month = factor(c("Nov", "Dec", "Jan", "Feb")),
count = c(1489, 788, 823, 1002))
g <- (ggplot2::ggplot(data, ggplot2::aes(x=month, y=count))
+ ggplot2::geom_bar(stat="identity")
+ ggplot2::scale_x_discrete(limits=rev(data$month))
+ ggplot2::coord_flip())
g
Run Code Online (Sandbox Code Playgroud)
...产生这个
将计数(1489、788 等)添加到相应栏的右侧的最简单方法是什么?
我对水平情况特别感兴趣,但我也想知道如何对垂直情况做类似的事情(计算在每个条形的顶部):
g <- (ggplot2::ggplot(data, ggplot2::aes(x=month, y=count))
+ ggplot2::geom_bar(stat="identity"))
g
Run Code Online (Sandbox Code Playgroud)
您正在寻找geom_text。您也不应该ggplot2在每次调用包中的函数时都需要指定该包(尽管我不知道您还加载了哪些内容!)。您应该注意的水平和垂直之间的唯一区别是hjustvsvjust参数,它可以水平或垂直调整标签的位置。(我将它们放入是因为默认位置似乎与栏的边缘重叠。)
ggplot(data, aes(x=month,y=count)) +
geom_bar(stat="identity") +
scale_x_discrete(limits=(data$month)) +
geom_text(aes(label=count), vjust=-0.7)
ggplot(data, aes(x=month,y=count)) +
geom_bar(stat="identity") +
scale_x_discrete(limits=(data$month)) +
geom_text(aes(label=count), hjust=-0.3) +
coord_flip()
Run Code Online (Sandbox Code Playgroud)