如何分别绘制每行并将其保存为行名

时间:2019-01-25 05:12:10

标签: r

我已经读过这个Plot all rows of a data frame with ggplot

我正在尝试绘制数据的每一行并保存

df <- structure(list(X1 = c(0.006605138, 0.001165448, 0.006975109, 
0.002207839, 0.00187902, 0.002208638, 0.001199808, 0.001162252, 
0.001338847, 0.001106317), X2 = c(0.006041392, 0.001639298, 0.006140877, 
0.002958169, 0.002744017, 0.003107995, 0.001729594, 0.001582564, 
0.001971713, 0.001693236), X3 = c(0.024180351, 0.002189061, 0.027377442, 
0.002886651, 0.002816333, 0.003527908, 0.00231891, 0.001695633, 
0.00212034, 0.001962923)), row.names = c("AA", "AB", "AC", "AF", 
"AD", "JJ", "JA", "NM", "KA", "LF"), class = "data.frame")

我正尝试一张一张地绘制它,然后像这样保存它

plot(df[1,],length(df),type="l")

enter image description here

1 个答案:

答案 0 :(得分:2)

您可以将数据转换为长格式,以使每个数据的x和y线都在列中,然后使用dlply分别绘制每个名称(以前是每行)。如果需要,还可以添加呼叫以将图保存在其中。

library(plyr)
library(tidyverse)
df_l <- df %>% rownames_to_column("Name") %>% gather(Var, Value, -Name) %>%
  arrange(Name) %>% group_by(Name) %>% mutate(n=row_number()) 

plotlist <- dlply(df_l, .(Name),
                  function(x) ggplot(x, aes(x = n, y = Value))+
                       geom_point()+geom_line())

或者保存而不是分配给变量

d_ply(df_l, .(Name),
                  function(x) (ggplot(x, aes(x = n, y = Value))+
                    geom_point()+geom_line()) %>% 
       ggsave(., filename =  paste0("plt", x$Name[1],".jpg")))

假设您希望它们位于当前工作目录中