1
votes

I am making a personality survey that will generate score reports for participants. I want to make these as easy to read and understand as possible, so I am generating a normal curve for the surveyed trait and a line showing the person where they fall on the curve.

First, let's generate some data:

sample <- as.data.frame(rnorm(1000, 0, 1))
names(sample) <- "trait"
score <- mean(sample$trait)

My problem is with the legend—I cannot figure out how to customize the legend to display 1) a filled "population" color when I'm not graphing multiple factors, and 2) the line showing the participant's score.

I can get close:

ggplot(sample, aes(x=trait)) +
 geom_density(fill="blue") +
 geom_density(aes(fill="Population")) +
 geom_vline(aes(xintercept=score, color="You")) +
 geom_vline(xintercept=score, color='red',
         linetype="solid",size=1.5) +
 scale_colour_manual(values=c('Population'='blue', 
                                    'You'='red'))

Graph image 1

enter image description here

But this does not use the colors specified, and has extraneous "colour" and "fill" text in the legend.

If I change the geom_density aesthetic to color instead of fill and leave everything else the same...

geom_density(aes(color="Population")) +

...This correctly applies the colors, but then does not fill the "Population" box in the legend with blue.

Graph image 2

enter image description here

Optimally, I'd like to fill the "Population" box blue and remove the red box around the "You" line in the legend. How can I achieve this?

1
You need scale_fill_manual if you want to change fill colorTung
Ah, thank you! That works, along with adding an empty 'name' in scale_fill_manual to remove the labels.TerribleClaw
You can post an answer to your own question to help future readersTung

1 Answers

0
votes

I hope this can be used.

ggplot(sample, aes(trait)) +
    geom_density(aes(fill = "Population")) +
    geom_vline(aes(xintercept = mean(trait), color = "You")) +
    theme(legend.title = element_blank()) +
    scale_color_manual(values = "red", breaks = "You") +
    scale_fill_manual(values = "blue", breaks = "Population")

enter image description here