Elizabeth
Elizabeth

Reputation: 241

R ggplot: colour and fill arguments

I am new in R and just started to learn ggplot. I am so confused by the syntax, I thought the "color" and "fill" arguments should always follow color names or RGB specifications. But I've seen many cases where "color" and "fill" in aes() were assigned with variables, see the below example.

ggplot(faithfuld, aes(waiting, eruptions)) +
  geom_raster(aes(fill = density))

I couldn't find an explanation of such use in [R documentation][1]. What does it mean? coloring by factor/grouping? if fill and color are assigned with variables, where should colors be specified? in scale_colour_manual?

Besides, I noticed that if specifying colors and/or transparency in aes(), the specified colors or transparency won't realise. For instance, in the below code, alpha = 0.3 is not working, I can change the alpha to any value, and the transparency will always be 0.5 in plotting. Why is that?

Also, I noticed that if I deleted fill or alpha in the aex(), the following "scale_fill_manual" wouldn't work. So is it true that "scale_fill_manual" is dependent on the geom_xx()?

p <- ggplot(dfcc) + geom_ribbon(aes(x = yr, ymax = ciupper, ymin = cilower, fill = "", alpha = 0.3)) +
  scale_fill_manual(values = "blue", labels = "CI95%") 

Sorry for so many questions, I am just so confused, and any help will be appreciated! [1]: https://search.r-project.org/CRAN/refmans/ggplot2/html/aes_colour_fill_alpha.html

Upvotes: 0

Views: 14058

Answers (1)

Grasshopper_NZ
Grasshopper_NZ

Reputation: 765

Please read Chapter 3 of R for Data Science when you got some time, it may answer your question (Section 3.3):

You can convey information about your data by mapping the aesthetics in your plot to the variables in your dataset.

As examples, please see and observe the differences among these 3 set of code and their outputs:

  1. Use Red as color:

    iris |> 
      ggplot(aes(x = Sepal.Length, y = Sepal.Width)) +
      geom_point(color = "red") +
      theme_minimal() +
      theme(panel.grid = element_blank())
    

    You get:

    enter image description here

  2. Use Species as color:

    iris |> 
      ggplot(aes(x = Sepal.Length, y = Sepal.Width)) +
      geom_point(aes(color = Species)) +
      theme_minimal() +
      theme(panel.grid = element_blank())
    

    You get:

    enter image description here

  3. Modify Species with the color of your choice:

    iris |> 
      ggplot(aes(x = Sepal.Length, y = Sepal.Width)) +
      geom_point(aes(color = Species)) +
      theme_minimal() +
      theme(panel.grid = element_blank()) +
      scale_color_manual(values = c("red", "yellow", "purple"))
    

    You get:

    enter image description here

Upvotes: 2

Related Questions