0

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?

io_boh
  • 193
  • 7
  • You must give grouping column name from your dataset in the fill= option. For example fill = group. The group column in your dataset – S-SHAAF Feb 25 '23 at 16:58
  • 2
    If you put `colour = "red"` inside the `aes()` function, you map it to a scale. If you use it outside the `aes()` function, you use it directly without going through a scale. – teunbrand Feb 25 '23 at 17:22

1 Answers1

1

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.

Oliver
  • 8,169
  • 3
  • 15
  • 37