Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot2: Factor for x axis with geom_line doesn't work

Tags:

r

ggplot2

I want a line plot, where value is plotted as a function of expt with one line per level in var:

Here is my data:

lines <- "
expt,var,value
1,none.p,0.183065327746799
2,none.p,0.254234138384241
3,none.p,0.376477571234912
1,male.p,-1.58289835719949
2,male.p,-1.98591548366901
3,male.p,-2.02814824729229
1,neutral.p,-2.01490302054226
2,neutral.p,-1.88178562088577
3,neutral.p,-1.68089687641625
1,female.p,-3.27294304613848
2,female.p,-3.07711187982237
3,female.p,-2.89652562347054
1,both.p,-2.40011011312792
2,both.p,-2.24495598015741
3,both.p,-2.78501124223834"
con <- textConnection(lines)
data <- read.csv(con)
close(con)

expt is a factor:

data$expt <- factor(data$expt)

Everything works as expected when I use geom_point

ggplot(data, aes(expt, value, colour=var)) + geom_point()

but when I use geom_line

ggplot(data, aes(expt, value, colour=var)) + geom_line()

I get the following error message

geom_path: Each group consists of only one observation. Do you need to adjust the group aesthetic?

and an empty plot. When expt is numeric, it works but I prefer to use a factor because that gives me the correct labels on the x-axis. What's the problem here? I find it very counter-intuitive that this works with points but not with lines.

like image 216
tmalsburg Avatar asked Jul 29 '16 23:07

tmalsburg


People also ask

Why does my Ggplot not have a line?

The answer is that the X variable is a factor type.

How do I change the size of a line in ggplot2?

To change line width, just add argument size=2 to geom_line().

How do I connect dots in ggplot2?

Connecting Paired Points with lines using geom_line() In ggplot2 we can add lines connecting two data points using geom_line() function and specifying which data points to connect inside aes() using group argument. Now we get a scatter plot connecting paired data with lines.


1 Answers

To plot a line graph with factors on the x-axis, you need to use group in addition to color...

ggplot(data, aes(expt, value, group=var, color=var)) + geom_line()

Gives me this output:

enter image description here

like image 147
beroe Avatar answered Oct 14 '22 00:10

beroe