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() |
将产生以下输出:
但是,我想获得以下输出:
另一个选项是
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")) |
如@Roland所建议,您可以使用
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)) |
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)) |
结果是:
也可以按以下方式使用
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)) |
如果在
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | library(dplyr) library(ggplot2) tribble( ~n, ~value, 100000, 20, 200000, 30, 300000, 25, 400000, 40, 500000, 12 ) %>% ggplot(aes(n, value)) + geom_point() + geom_line() + geom_text(aes(label=value), nudge_y=1, nudge_x=-10000) |
这基本上与调用
相同
1 2 3 4 | ggplot(data, aes(n, value)) + geom_point() + geom_line() + geom_text(aes(label=value), nudge_y=1, nudge_x=-10000) |