Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plotting a single line with two different colours with ggplot2

I'm trying to plot a set of data with ggplot2. The data are in two categories. I would like to plot them together, with a single linear regression line. However, I would like to have each of the two groups plotted in different colours. Here's what I get:

enter image description here

Here's how I got it:

library(ggplot2)
dframe1 <- structure(list(a = 1:6, b = c(5, 7, 9, 10.5, 11.7, 17), category = structure(c(1L, 
1L, 1L, 2L, 2L, 2L), .Label = c("a", "b"), class = "factor")), .Names = c("a", 
"b", "category"), class = "data.frame", row.names = c(NA, -6L
))
qplot(a, b, data = dframe1, colour = category) + geom_smooth(method = lm)

How do I make the plot only use one regression line for all the data?

Note: Quite apart from this, I'm puzzled as to why only one of these lines has confidence intervals shown, but that's not the point of my current question.

like image 921
CaptainProg Avatar asked Aug 24 '26 13:08

CaptainProg


1 Answers

The equivalent of @Roland's answer, using ggplot instead of qplot

ggplot(dframe1, aes(x = a, y = b)) +
    stat_smooth(method = lm) +
    geom_point(aes(color = category))
like image 132
Gregor Thomas Avatar answered Aug 26 '26 02:08

Gregor Thomas