仅在条形图上显示最后四个标签

时间:2015-06-02 21:16:01

标签: r ggplot2

我的代码在这里生成一个条形图,在y值的每个条上都有标签 我想只显示最后4个数据点作为标签。最好的方法是什么? enter image description here

library(data.table)
library(ggplot2)

df <- data.table(x= c(1,2,3,4,5,6,7,8,9,10), y=c(4,1,-3,-5,4,1,2,4,2,-3))

ggplot(df, aes(x=x, y=y)) +
        geom_bar(stat="identity") +
        geom_text(aes(y=y, ymax=y, label=y), 
                  position= position_dodge(width=0.9), vjust=-.5, color="red")

非常感谢你。

1 个答案:

答案 0 :(得分:2)

感谢@ user20650的快速回复。子设置gem_text就可以了。非常感谢你!

以下是更新后的代码:

library(data.table)
library(ggplot2)

df <- data.table(x= c(1, 2, 3, 4, 5,6,7,8,9,10), y=c(4, 1,-3,-5,4,1,2,4,2,-3))

ggplot(df, aes(x=x, y=y)) +
        geom_bar(stat="identity") +
        geom_text(data=subset(df, x>6), aes(y=y, ymax=y, label=y), 
                  position= position_dodge(width=0.9), vjust=-.5, color="red")

enter image description here

相关问题