如何重塑此数据以使用ggplot2绘制多行?

时间:2017-09-11 19:05:48

标签: r ggplot2 reshape reshape2 melt

我有一个如下所示的数据框:

    lethal.y         lethal.x         resist.y         resist.x          mock.y           mock.x      
 Min.   :0.0000   Min.   :0.0000   Min.   :0.0000   Min.   :0.0000   Min.   :0.0000   Min.   :0.0000  
 1st Qu.:0.3724   1st Qu.:0.4349   1st Qu.:0.6580   1st Qu.:0.3102   1st Qu.:0.5065   1st Qu.:0.5143  
 Median :0.6786   Median :0.8688   Median :0.9889   Median :0.6034   Median :0.9105   Median :0.9305  
 Mean   :0.5943   Mean   :0.6961   Mean   :0.8086   Mean   :0.5645   Mean   :0.7337   Mean   :0.7445  
 3rd Qu.:0.8229   3rd Qu.:0.9791   3rd Qu.:1.0000   3rd Qu.:0.8236   3rd Qu.:0.9863   3rd Qu.:0.9970  
 Max.   :1.0000   Max.   :1.0000   Max.   :1.0000   Max.   :1.0000   Max.   :1.0000   Max.   :1.0000

每个项目有100行,* .x和* .y表示我想为这三个条件中的每一个绘制的x,y坐标。

我想用ggplot2在不同颜色的相同图中绘制这三个图。我相信我需要将数据框融合成(例如:

variable     x       y
lethal      .05     .01
lethal      .03     .02
...
resist 
...
mock  

我只是不确定如何重塑数据。谁能指出我正确的方向?谢谢!

根据要求,dput(head(df))

structure(list(lethal.y = c(1, 0.96880698743694, 0.943637604878407, 
0.927797183915007, 0.913304798925335, 0.898733226540142), lethal.x = 
c(0, 
0.00188975165738148, 0.017044638907188, 0.0473993105875835, 
0.0839965839587461, 
0.123115782372135), resist.y = c(1, 1, 1, 1, 1, 1), resist.x = c(0, 
0.0270024232342251, 0.0532702535247161, 0.0802380777311505, 
0.106711277307466, 
0.131788524427236), mock.y = c(1, 0.99663149455591, 
0.994833858282874, 
0.992162832558697, 0.9898151419445, 0.98845829511382), mock.x = c(0, 
0.0422315106004306, 0.0848393643462402, 0.127812802135558, 
0.17073684383134, 
0.212410640574118)), .Names = c("lethal.y", "lethal.x", "resist.y", 
"resist.x", "mock.y", "mock.x"), row.names = c(NA, 6L), class = 
"data.frame")

1 个答案:

答案 0 :(得分:1)

在这种情况下,您实际上不必转换数据。试试这个:

require(ggplot2)

ggplot(df) +
  geom_line(aes(x=lethal.x,y=lethal.y,col="lethal")) +
  geom_line(aes(x=resist.x,y=resist.y,col="resist")) +
  geom_line(aes(x=mock.x,y=mock.y,col="mock")) +
  xlab("") +
  ylab("") +
  guides(col=guide_legend("Variable"))

输出:

enter image description here