简体   繁体   English

如何使 alpha(透明度)在 ggplot 图例中显示为连续渐变?

[英]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?是否可以使透明度(alpha)在 ggplot 图例中显示为连续渐变? Currently, the plot looks like this:目前,情节如下所示: 在此处输入图像描述

Here, the different values for alpha are represented by dots in a different transparency.在这里,不同的 alpha 值由不同透明度的点表示。 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):我希望它被表示为具有连续透明度渐变的条形,如下图所示(但作为透明度渐变而不是颜色): 在此处输入图像描述

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") 

You can't have a color bar as the guide for an alpha scale.您不能将颜色条作为 alpha 比例的指南。 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.如果您已经在使用色标(如您的示例中所示),最好为您的两个虚拟变量中的每一个设置一个 alpha 颜色条。 For this you need the ggnewscale package为此,您需要ggnewscale

Obviously, I don't have your data, so here's a working example with the built-in mtcars data set.显然,我没有你的数据,所以这里有一个内置mtcars数据集的工作示例。

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)

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM