0

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.

Mike49
  • 473
  • 1
  • 5
  • 17
  • What happens if you remove the `group=candidate`? – WhipStreak23 Jul 01 '20 at 11:49
  • I get the same error – Mike49 Jul 01 '20 at 11:51
  • 1
    It seems from your screenshot that your candidate column is of the type `>`, probably added as column with `grouped_covid$candidate <- I(some_variable)`. Try converting it to a plain character and running your plotting code again. Also @WhipStreak23's latest suggestion to use the `$`-operator inside `aes()` is generally not a good practise. – teunbrand Jul 01 '20 at 12:02
  • I'm new to R, can you elaborate on what the type > is and how I should convert it to plain character? – Mike49 Jul 01 '20 at 12:10
  • @teunbrand I am aware of using the `$` inside `aes()` is bad practice, however, it has worked for me occasionally when the more conventional way fails. – WhipStreak23 Jul 01 '20 at 12:41
  • 1
    @Mike49 You can convert it to the plain character by using the [toString](https://rdrr.io/r/base/toString.html) or as.character function. – WhipStreak23 Jul 01 '20 at 12:46
  • @teunbrand and mike49 - actually I did not know you could use `I()` instead of scale...identity. kind of fun. :) – tjebo Jul 01 '20 at 12:57
  • 1
    @Tjebo me neither, but it appears to be a feature as there exists a `scale_type.AsIs` S3 method for automatically determining the scale, and it returns the "identity" scale. – teunbrand Jul 01 '20 at 13:18

1 Answers1

2

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

tjebo
  • 21,977
  • 7
  • 58
  • 94