Warm tip: This article is reproduced from stackoverflow.com, please click
ggplot2 r

ggplot2 not using default colors on fresh install. Appears to be viridis

发布于 2020-03-27 10:27:49

While working through some examples from Wickham's book ggplot2, I noticed that the discrete dot plot was using viridis colors which was installed and used elsewhere, but was not the scale for this plot.

R was installed on this computer for the first time this morning. Even when I run it outside of RStudio I get the same effect. I uninstalled R and Rstudio, deleted the R folder in my docs, and in program files. Reinstalled from the same exe download as before.

A fresh install, with the code snip below resulted in the same. viridis was not installed.

Not enough rep for images :

enter image description here

install.packages("tidyverse")
library(tidyverse)

colorcut = diamonds %>%
  group_by(color, cut) %>%
  summarize(
    price = mean(price),
  )

ggplot(colorcut, aes(color, price, color = cut)) +
  geom_point()
Questioner
Hunter
Viewed
30
MrFlick 2019-07-03 23:39

As mentioned above, viridis is the new default for ordered factors (not "regular" factors) as of v3.0.0. You can manually specify the palette you like

ggplot(colorcut, aes(color, price, color = cut)) +
  geom_point() + 
  scale_color_hue()

Of if you don't really want ordered factors to begin with, you can remove the ordered flag. Here's a function that can unorder a factor and as a consequence give you the default coloring

unorder <- function(x) {
  class(x) <- setdiff(class(x), "ordered")
  x
}

ggplot(colorcut, aes(color, price, color = unorder(cut))) +
  geom_point()

enter image description here

An "unordered factor" will still preserve it's levels. It's just in some cases ordered factors are used to indicated when methods for ordinal variables should be use rather than methods for discrete variables. But generally they behave much in the same way.