1
votes

I'm trying to generate a density plot using ggplot in which the color and fill of the plot is determined by one parameter and the alpha of the fill is determined by a second parameter.

I can get the figure to render the way that I want but in the legend the value of alpha is not depicted.

Since I am setting the values of alpha to 0 and 0.3, I would hope that the legend would show boxes with the corresponding opacity, (i.e. a white one and a gray one). Instead there are two boxes with the same opacity.

Any suggestions will be greatly appreciated.

I have recreated the issue with an example plot using mtcars

ggplot(
  mtcars,
  aes(
    x=wt,
    fill=factor(cyl),
    color=factor(cyl),
    alpha=factor(am)
  )
) +
  geom_density() +
  scale_alpha_discrete(
    name="transmission",
    labels=c("auto","manual"),
    range = c(0,0.3)
  ) +
  theme_bw()

enter image description here

1
I would suggest using different linetypes or facets instead of alpha.Martin Schmelzer
Thanks for the suggestion. I'm already using facets in figure to separate out one parameter, but changing linetype is a good idea. For aesthetics, I was hoping to do it with alpha.SubstantiaN

1 Answers

1
votes

The transmissions (factor(am)) don't have a color associated with them and only an alpha level. As a result the legend shows the 0% and 30% transparency of white, which is the default color. So alpha is rendered, but you just don't see it. You can solve this by filling the transmissions with for instance black in the legend.

ggplot(
    mtcars,
    aes(
        x=wt,
        fill=factor(cyl),
        color=factor(cyl),
        alpha=factor(am)
    )
)+
    geom_density()+
    scale_alpha_discrete(
        name="transmission",
        labels=c("auto","manual"),
        range = c(0,0.3)
    )+
    theme_bw()+
   guides(alpha = guide_legend(override.aes = list(fill = c('black','black'))))

enter image description here