简体   繁体   中英

R: Issues changing ggplot fill colors with scale_fill_manual

Following the Cookbook for R ( http://www.cookbook-r.com/Graphs/Legends_(ggplot2) ), I'm trying to change the legend and colors of the points and lines in a plot in ggplot using scale_fill_manual, but it doesn't seem to be working—the geom_points stay black, and the geom_smooths stay blue. Here is reproducible code:

type <- c("0", "0", "1", "2", "2", "2", "2", "1")
votes <- c(21, 28, 52, 66, 65, 42, 48, 39)
time <- c(1, 2, 3, 4, 5, 6, 7, 8)
df <- data.frame(type, votes, time)

test.plot <- ggplot(df, aes(y = votes, x = time, fill = type)) +
geom_point() +
geom_smooth(lwd = 0.75, lty = "dashed", se = FALSE, method = lm) +
scale_fill_manual(values=c("blue4", "purple4", "red4"),
                breaks=c("2","1","0"),
                labels=c("Standard", "Nonstandard", "Oddball"),
                name="Type")
test.plot

I'm trying to have the points and lines labeled "Standard" show up dark blue, the "Nonstandard" points and lines show up dark purple, and the "Oddball" points and lines show up dark red, but the points all show up black and the lines all show up blue:

! https://i.stack.imgur.com/IylCg.jpg

Anyone have a fix? Thank you in advance!

Generally, I'd suggest remapping the variable before plotting since it makes for easier code (and means you can check the values in the data first):

df$type <- factor(df$type, levels = 0:2,
                  labels = c("Oddball", "Nonstandard", "Standard"))

test.plot <- ggplot(df, aes(y = votes, x = time, colour = type)) +
  geom_point() +
  geom_smooth(lwd = 0.75, lty = "dashed", se = FALSE, method = lm) +
  scale_colour_manual(values=c("Standard" = "blue4", "Nonstandard" = "purple4",
    "Oddball" = "red4"), name="Type")

However, otherwise, you just need to change the aesthetic to colour instead of fill :

test.plot <- ggplot(df, aes(y = votes, x = time, colour = type)) +
  geom_point() +
  geom_smooth(lwd = 0.75, lty = "dashed", se = FALSE, method = lm) +
  scale_colour_manual(values=c("blue4", "purple4", "red4"),
                    breaks=c("2","1","0"),
                    labels=c("Standard", "Nonstandard", "Oddball"),
                    name="Type")

情节

Note lines and points use colour rather than fill and you just need a named vector argument for scale_x_manual .

If your levels aren't syntactic as name s, you'll need to surround them with double quotes (eg "Non-standard" ).

See also the manual .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM