Mike49
Mike49

Reputation: 473

ggplot color is not automatically coloring based on group

I'm trying to create to lines on a graph by group 'candidate'Dataset

My code is ggplot(grouped_covid, aes(x=newDate, y = positiveIncrease, group=candidate, color = candidate)) + geom_line()

When I set color = candidate, I get Error: Unknown colour name: Clinton, Hillary. My understanding is that it should just automatically set the color based on the grouping under candidate but it seems think I am trying to define the colors.

Upvotes: 0

Views: 1928

Answers (1)

tjebo
tjebo

Reputation: 23797

@teunbrand was spot on. Interesting. You may have somehow more or less voluntarily used I(), which lets R interpret an object "as is". See also ?I

Here how to convert back to plain character:

You can do that either temporarily in the call to ggplot itself, or more permanently, by assignment (which I think you want to do).

update in the comments, user teunbrand pointed to the S3 Method scale_type.AsIs, which is why using an "asIs" object works just like using scale...identity

## this is to reproduce your data structure
iris2 <- iris
iris2$Species <- I(as.character(iris2$Species))

library(ggplot2)
ggplot(iris2, aes(x=Sepal.Length, y = Sepal.Width, color = Species)) + 
  geom_point()
#> Error: Unknown colour name: setosa

#convert withing ggplot
ggplot(iris2, aes(x=Sepal.Length, y = Sepal.Width, color = as.character(Species))) + 
  geom_point()

## convert by assignment
iris2$Species <- as.character(iris2$Species)

ggplot(iris2, aes(x=Sepal.Length, y = Sepal.Width, color = Species)) + 
  geom_point()

Created on 2020-07-01 by the reprex package (v0.3.0)

Upvotes: 2

Related Questions