使用R

时间:2017-05-10 12:54:50

标签: r dataframe plot

我有一个如下数据框:

    S1   S2   S3   Id
A   1.2  NA   3    lab1
B   -2   -0.5 1    lab1
C   -3   -0.5 NA   lab1
D   1    2    1    lab1
A   3    NA   1    lab2
B   -2   -0.5 1    lab2
D   0.5  0.5  NA   lab2
E   4    2    1    lab2

我想针对三个时间点IdS1S2制作一个带有S3所示标签的点图。另外,如果可能的话,我还想将row.names的名称添加为标签。这样,在S1,我会有两个标记为A的点,但有2种不同的颜色而不是叠加,2个点标记为B,有2种不同的颜色但叠加了。

我试图使用plot,它允许你在R中绘制顺序数据,但直到现在我一直不幸。该图将给出值,忽略NA,作为三个步骤的函数。我是否需要转置我的DF,并为三个步骤c(1,2,3)S1S2分配索引(例如S3),然后绘制它,或者是否有避免转置和添加此类信息的方法? 你能给我一些关于如何绘制这个的提示吗?感谢

2 个答案:

答案 0 :(得分:2)

假设你的数据在dat1。

dat1 <- structure(list(Col = c("A", "B", "C", "D", "A", "B", "D", "E"
), S1 = c(1.2, -2, -3, 1, 3, -2, 0.5, 4), S2 = c(NA, -0.5, -0.5, 
2, NA, -0.5, 0.5, 2), S3 = c(3L, 1L, NA, 1L, 1L, 1L, NA, 1L), 
    Id = c("lab1", "lab1", "lab1", "lab1", "lab2", "lab2", "lab2", 
    "lab2")), .Names = c("Col", "S1", "S2", "S3", "Id"), class = "data.frame", row.names = c(NA, 
-8L))

您可以使用ggplot2来做同样的事情,我希望我能正确理解您的问题。您需要将您的rownames作为变量/列,然后融入长格式数据以绘制此图。可以有其他不同的方式。 要融化数据,您可以使用从reshape2收集或融化。要绘制我正在使用ggplot2。

library(tidyverse)
library(reshape2)
df_melt <- melt(dat1,id.vars= c("Col","Id")) 
df_melt %>%
  ggplot(aes(x = Col, y = value, color = Id)) +
  geom_point() +
  facet_wrap(~ variable, scales = "free") +
  theme_bw()

另一种看待它的方式:

df_melt %>%
  ggplot(aes(x = variable, y = value, color = Id)) +
  geom_point() +
  facet_wrap(~ Col, scales = "free") +
  theme_bw()

第一个ggplot的预期输出:

enter image description here

第二个ggplot的预期输出:

enter image description here

答案 1 :(得分:2)

您可以尝试以下方法:

library(data.table)
library(ggrepel)
library(ggplot2)

data <-  fread('label   S1   S2   S3   Id
                A   1.2  NA   3    lab1
                B   -2   -0.5 1    lab1
                C   -3   -0.5 NA   lab1
                D   1    2    1    lab1
                A   3    NA   1    lab2
                B   -2   -0.5 1    lab2
                D   0.5  0.5  NA   lab2
                E   4    2    1    lab2')


temp <- melt(data, id.vars = c("label", "Id"))


ggplot(temp, aes(x = variable, y = value, color = Id)) + 
      geom_point() +
      geom_text_repel(aes(label=label), show.legend = F)

这会给你: enter image description here