R ggplot2:如何在紧挨着它的每个数据点上写y坐标?


R ggplot2: how to write the y coordinate of every data point right next to it?

数据集示例:

1
2
3
4
5
6
n   value
100000  20
200000  30
300000  25
400000  40
500000  12

以下代码:

1
2
3
4
5
require(ggplot2)
data <- read.table("test", sep ="\\t", header = TRUE,)
ggplot(data, aes(n, value)) +
geom_point(aes(n,value)) + geom_line(aes(n,value))
dev.off()

将产生以下输出:

enter


另一个选项是library(ggrepel),以自动最小化点/标签的重叠。我认为它比position_jitter()更可靠,并且在您不能/不想对所有闪避值进行硬编码时很有用:

1
2
3
4
5
6
ggplot(data, aes(n, value)) +
    geom_point() +
    geom_line() +
    # geom_text(aes(label = value), position ="jitter")
    geom_text_repel(aes(label = value),
                    point.padding = unit(.25,"lines"))

geom_label_repel()也可用,并且有很多选项可以设置" dodge "区域大小。

enter

1
2
3
4
5
6
7
8
data <- structure(list(n = c(100000L, 200000L, 300000L, 400000L, 500000L
), value = c(20L, 30L, 25L, 40L, 12L)), .Names = c("n","value"
), class ="data.frame", row.names = c(NA, -5L))

library(ggplot2)
ggplot(data, aes(x=n, y=value)) +
geom_point(aes(n,value)) + geom_line(aes(n,value))+
geom_text(aes(label=value), hjust=c(-1,0,0,-1,2), vjust=c(1,-.5,1.5,0,0))

enter

1
2
3
ggplot(data, aes(x=n, y=value)) +
geom_point(aes(n,value)) + geom_line(aes(n,value))+
geom_label(aes(label=value), hjust=c(-1,0,0,-1,2), vjust=c(1,-.5,1.5,0,0))

结果是:

enter

1
2
3
4
ggplot(data, aes(x=n, y=value)) +
geom_point(aes(n,value)) + geom_line(aes(n,value))+
annotate("text", x=data$n, y=data$value, label=data$value,
   hjust=c(-1,0,0,-1,2), vjust=c(1,-.5,1.5,0,0))