如何在ggplot中添加带索引的另一个标签

时间:2017-08-03 17:16:08

标签: r

我有这样的数据

df<- structure(list(ID = structure(c(12L, 3L, 10L, 5L, 2L, 7L, 11L, 
6L, 1L, 4L, 9L, 8L), .Label = c("O00330", "P18085", "P48507", 
"P49588", "P68104", "Q02338", "Q71UM5", "Q86X55", "Q8N8R3-1", 
"Q96D46", "Q9HC98-2", "Q9UBS4"), class = "factor"), S1 = c(9.202092, 
8.235443, 8.041566, 8.573015, 7.304765, 7.713755, 7.295146, 7.244745, 
7.34637, 7.11046, 7.644448, 6.602916), S2 = c(4.601046, 4.117722, 
4.020783, 8.521702, 3.652383, 3.856877, 3.647573, 3.622372, 3.673185, 
3.55523, 3.822224, 3.301458), S3 = c(42.99771, 37.97722, 37.81253, 
37.56675, 34.14236, 33.68886, 33.46629, 33.25362, 32.74997, 32.35916, 
30.98728, 30.65774)), .Names = c("ID", "S1", "S2", "S3"), row.names = c(NA, 
-12L), class = "data.frame")

我尝试用另一种颜色绘制它和特定点

index1 <- as.integer(c(1,2,4,6))
index2 <- as.integer(c(3,7))

library(ggplot2)

    ggplot(data=df, aes(x = S1, y = S2)+
      geom_point(colour="blue",size=1)+ 
      geom_point(data=df[index1, ], aes(x = S1, y = S2), colour="red", size=2)+
      geom_point(data=df[index2, ], aes(x = S1, y = S2), colour="green", size=3)+
      geom_text(data=df[index1, ], aes(x = S1, y = S2, label=ID),hjust = 0, nudge_x = 0.1))+
      geom_text(data=df[index2, ], aes(x = S1, y = S2, label=ID),hjust = 0, nudge_x = 0.1))

我想换另一个名字而不是那些索引的ID

例如索引6

1 ----> NAT
2-----> BER2
4-----> RAMS
6-----> RATA

和索引2

3 ----> NAYT
7-----> BER7

1 个答案:

答案 0 :(得分:0)

我创建了一个查找表

df2 <- data.frame(ID = df$ID, Names = c("NAT", "BER2","NAYT",
  "RAMS",NA,"RATA","BER7",NA,NA,NA,NA,NA))

dfNew <- merge(df,df2)

输出:

         ID       S1       S2       S3 Names
1    O00330 7.346370 3.673185 32.74997  <NA>
2    P18085 7.304765 3.652383 34.14236  <NA>
3    P48507 8.235443 4.117722 37.97722  BER2
4    P49588 7.110460 3.555230 32.35916  <NA>
5    P68104 8.573015 8.521702 37.56675  RAMS
6    Q02338 7.244745 3.622372 33.25362  <NA>
7    Q71UM5 7.713755 3.856877 33.68886  RATA
8    Q86X55 6.602916 3.301458 30.65774  <NA>
9  Q8N8R3-1 7.644448 3.822224 30.98728  <NA>
10   Q96D46 8.041566 4.020783 37.81253  NAYT
11 Q9HC98-2 7.295146 3.647573 33.46629  BER7
12   Q9UBS4 9.202092 4.601046 42.99771   NAT