将标签或geom_text添加到散点图-R / ggplot2

时间:2018-07-05 05:17:39

标签: r ggplot2

如何为每个包含其数据帧索引以及xvar和yvar值的点添加标签/ geon_text(例如,第一个标签为(“点1:500,570”)?

代码:

library(ggplot2))

xvar <- c(500,450,490,560,618, 660,700,650, 590,550)
yvar <- c(570,600,650,670,660,650,630,580,570,550)
dat <- data.frame(xvar,yvar)

ggplot(dat, aes(x=xvar, y=yvar)) + geom_point(shape=1)  

2 个答案:

答案 0 :(得分:1)

创建一个变量标签并将其打印到geom_text()

库(ggplot2)

> xvar <- c(500,450,490,560,618, 660,700,650, 590,550)
> yvar <- c(570,600,650,670,660,650,630,580,570,550)
> dat <- data.frame(xvar,
                    yvar)

> dat$point <- sprintf("Point %s",
                       seq(from = 1,
                           to = length(xvar)))

> dat$labvar <- sprintf("%s: %s, %s",
                        dat$point,
                        dat$xvar,
                        dat$yvar)

> dat
   xvar yvar    point             labvar
1   500  570  Point 1  Point 1: 500, 570
2   450  600  Point 2  Point 2: 450, 600
3   490  650  Point 3  Point 3: 490, 650
4   560  670  Point 4  Point 4: 560, 670
5   618  660  Point 5  Point 5: 618, 660
6   660  650  Point 6  Point 6: 660, 650
7   700  630  Point 7  Point 7: 700, 630
8   650  580  Point 8  Point 8: 650, 580
9   590  570  Point 9  Point 9: 590, 570
10  550  550 Point 10 Point 10: 550, 550

> ggplot(dat, aes(x=xvar,
                  y=yvar)) +
    geom_text(aes(label = labvar),
              hjust = -0.05,
              vjust = 0.05) +
    geom_point(shape = 1)

labelled graph

答案 1 :(得分:0)

 library(ggplot2)
 library(ggrepel)
 library(dplyr)

 xvar <- c(500,450,490,560,618, 660,700,650, 590,550)
 yvar <- c(570,600,650,670,660,650,630,580,570,550)
 dat <- data.frame(xvar,yvar, xindex = seq_along(xvar)) %>% 
   dplyr::mutate(label = paste0("x: ", xvar, ", y:", yvar, ", index: ", xindex))

 ggplot(dat, aes(x=xvar, y=yvar)) + geom_point(shape=1)  + 
   geom_text_repel(aes(label = label))