glacierbliss
glacierbliss

Reputation: 102

why does ggplot plot lines differently when colors are factor vs numeric

I'm getting better at making ggplots, but can't figure out why lines get plotted differently when colors are based on continuous numbers vs discrete factors.

ggplot(iris, aes(x=Sepal.Length, y=Sepal.Width, color=Species)) +
  geom_line()+
  scale_color_brewer(palette = 'Blues')+
  labs(title='Discrete, class(Species) = factor')

The plot above connects all the setosa points together. The plot below draws vertical lines connecting setosa points with other species points. Why?

iris$SpeciesNum=as.numeric(iris$Species)
ggplot(iris, aes(x=Sepal.Length, y=Sepal.Width, color=SpeciesNum)) +
  geom_line()+
  scale_color_distiller(palette='Blues')+
  labs(title='Continuous, class(SpeciesNum) = numeric')

In my real case, there's over 50 color values and while there's no need for the viewer to distinguish color #1 from color #2, I'd like to use the continuous color option to get a nice gradient but have the points connected to one another in the way that the discrete plot does it. How can I do this?

Upvotes: 1

Views: 69

Answers (1)

glacierbliss
glacierbliss

Reputation: 102

Thanks Stephan, that did it!

Desired behavior:

ggplot(iris, aes(x=Sepal.Length, y=Sepal.Width, group=Species, color=SpeciesNum)) +
  geom_line()+
  scale_color_distiller(palette='Blues')+
  labs(title='group=Species, color=SpeciesNum, class(SpeciesNum) = numeric')

Upvotes: 1

Related Questions