'How to make alpha (transparency) appear as continuous gradient in the ggplot legend?

Is it possible to make the transparency (alpha) appear as a continuous gradient in the ggplot legend? Currently, the plot looks like this: enter image description here

Here, the different values for alpha are represented by dots in a different transparency. I would like it to be represented as a bar with a continuous transparency gradient as illustrated below (but as a gradient of transparency instead of color): enter image description here

The code I use for making the plot is this:

    df %>% 
  ggplot(aes(x = intraEU_trade_bymemberstate_pct,
             y = gini_eurostat, 
             alpha = year, 
             size = GDP_percap_currentUSD,
             color = as.factor(lowGDP_percap_currentUSD))) + 
    geom_point() + 
    geom_smooth(method="lm", formula = y ~ x, show.legend = FALSE, color = "#6c757d") +
    theme_few() + 
    scale_colour_manual(name="GDP per capita \n(dummy)",
                        labels = c("Above-average", "Below-average"), 
                        values = c("#046d9a", "#ce5348")) +
    scale_alpha_continuous(range = c(0.1, 1)) + 
    scale_size(range=c(0.3, 4)) + # control the size of the dots
    guides(alpha = guide_legend(order = 1), 
           size = guide_legend(order = 2),
           color = guide_legend(order = 3)) + 
    labs(x = "Intra-EU trade (% of total trade)",
         y = "Gini (%)",
         alpha = "Year",
         size = "GDP per capita \n(current USD)",
         color = "GDP per capita") 


Solution 1:[1]

You can't have a color bar as the guide for an alpha scale. However, you can set a color gradient in which one of the two colours is fully transparent, which amounts to the same thing.

If you are already using the color scale (as in your example), it would be best to have an alpha color bar for each of your two dummy variables. For this you need the ggnewscale package

Obviously, I don't have your data, so here's a working example with the built-in mtcars data set.

library(ggplot2)

ggplot(mtcars[1:16, ], aes(wt, disp)) +
  geom_point(aes(color = mpg), size = 3) +
  scale_color_gradient(low = alpha("navy", 0), high = "navy",
                       name = "Below average") +
  ggnewscale::new_scale_color() +
  geom_point(aes(color = mpg), data = mtcars[17:32,], size = 3) +
  scale_color_gradient(low = alpha("red3", 0), high = "red3",
                       name = "Above average") +
  theme_light(base_size = 16)

enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1