Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot2() plotting one variable against itself by factor?

Tags:

r

ggplot2

I'm trying to use ggplot to create a geom_point with two lines, typically these two lines are from two different variables within a dataframe e.g.

library(ggplot2)
ggplot(aes(x=var1,y=var2),data = df) + geom_point() 

However in this case I have one variable which is stacked vertically (representative of a replicate 1 and 2) and in another column there is a score (again from two replicates):

data.frame(fac=c(rep("trial1",10),rep("trial2",10)),score=rnorm(20,2,1))

What I want to do is a simple ggplot or line graph of trial 1 in y axis and trial 2 on x axis. In the base plot function this is simple to do as all it needs is for the data to be split into two different data frames. However in ggplot I always use the same data frame and from what I know I can't use two separate data frames for the call. So how do I do this?

I was guessing there was some work around using group_by to arrange data.frame prior to plotting but I wasn't sure how to implement it. I hope this is sufficiently clear.

like image 862
Dasr Avatar asked Jan 25 '26 11:01

Dasr


1 Answers

Using tidyverse functions, you can do

library(dplyr)
library(tidyr)
library(ggplot2)
dd %>% 
  group_by(fac) %>% 
  mutate(id=1:n()) %>% 
  spread(fac, score) %>% 
  ggplot(aes(trial2, trial1)) + 
  geom_line()

enter image description here

like image 144
MrFlick Avatar answered Jan 28 '26 05:01

MrFlick



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!