1
votes

I'm having trouble substituting color() for facet_grid() when I want to 'split' my data by a variable. Instead of generating individual plots with regression lines, I'm looking to generate a single plot with all regression lines.

Here's my code:

ggplot(data, aes(x = Rooms, y = Price)) +
    geom_point(size = 1, alpha = 1/100) +
    geom_smooth(method = "lm", color = Type) # Single plot with all regression lines
ggplot(data, aes(x = Rooms, y = Price)) +
    geom_point(size = 1, alpha = 1/100) +
    geom_smooth(method = "lm") + facet_grid(. ~ Type) # Individual plots with regression lines

(The first plot doesn't work) Here's the output: "Error in grDevices::col2rgb(colour, TRUE) : invalid color name 'Type' In addition: Warning messages: 1: Removed 12750 rows containing non-finite values (stat_smooth). 2: Removed 12750 rows containing missing values (geom_point)."

Here's a link to the data: Dataset

1
It's good to post reproducible data, but you didn't wrap your colour argument inside aes and instead passed it to geom_smooth directly.Calum You
Sure thing, I've added output and a link to the dataset.TypingDog

1 Answers

1
votes

You need to supply an aesthetic mapping to geom_smooth, not just a parameter, which means you need to put colour inside aes(). This is what you need to do any time you want to have an graphical element correspond to something in the data rather than a fixed parameter.

Here's an example with the built-in iris dataset. In fact, if you move colour to the ggplot call so it is inherited by geom_point as well, then you can colour the points as well as the lines.

library(ggplot2)
ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width)) +
  geom_point() +
  geom_smooth(aes(colour = Species), method = "lm")

ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width, colour = Species)) +
  geom_point() +
  geom_smooth(method = "lm")

Created on 2018-07-20 by the reprex package (v0.2.0).