Adam Price
Adam Price

Reputation: 850

How can I reshape this data to plot multiple lines with ggplot2?

I have a dataframe that looks like this:

    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

Each item has 100 rows, and the *.x and *.y indicate the x,y coords I want to plot for each of these three conditions.

I want to use ggplot2 to plot these three in the same plot with different colored lines. I believe I need to melt() the dataframe into something like:

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

I'm just not exactly sure how to reshape the data here. Can anyone point me in the right direction? Thanks!

As requested, 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")

Upvotes: 0

Views: 517

Answers (1)

www
www

Reputation: 4224

You don't actually have to transform the data in this case. Try this:

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"))

Output:

enter image description here

Upvotes: 1

Related Questions