CaptainProg
CaptainProg

Reputation: 5690

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.

Upvotes: 3

Views: 2891

Answers (2)

Gregor Thomas
Gregor Thomas

Reputation: 145765

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

Upvotes: 8

Roland
Roland

Reputation: 132676

Just modify the aesthetics to exclude the grouping factor:

qplot(a, b, data = dframe1, colour = category) + 
  geom_smooth(aes(colour=NA),method = lm)

enter image description here

Upvotes: 5

Related Questions