rggplot2colorslegenddensity-plot

is ggplot confused? It exchanges the color labels


I'm drawing density plot with ggplot, but in the output it inverts the name of the colors!

This is my script:

ggplot(dataset) + 
  geom_density( aes( x = `Real Wage 1`, fill = "red"), alpha = 0.5)+
  geom_density( aes( x = `Real Wage 2`, fill = "blue"), alpha = 0.5)+
  theme_classic()

Histograms

Why is this happening? Am I setting something wrong?


Solution

  • As mentioned by teunbrand, ggplot works by either grouping or individual colouring.

    Anything included in aes will be treated as if referring to a column or variable. If you specify a string in aes this'll be interpreted as a variable of length 1. To obtain the behaviour you're seeking specify fill outside the aes parameter

    ggplot(dataset) + 
      geom_density( aes( x = `Real Wage 1`), fill = "red", alpha = 0.5)+
      geom_density( aes( x = `Real Wage 2`), fill = "blue", alpha = 0.5)+
      theme_classic()
    

    A more thoughrough (and beginner friendly guide) to ggplot colouring is available at stdha. Give it a read, it is quite good for beginners and short.