首页 > 解决方案 > 如何将两种不同比例的颜色渐变与ggplot合并

问题描述

通过使用 R,是否可以将 2 个 ggplot 放在一起(即,在同一个图上)但具有不同的颜色渐变条?我的代码,例如,

library(ggplot2)
ggplot(df1, aes(duration, slopes, col = color)) +
 geom_point(size = 3) +
 scale_color_gradient(low = "black", high = "red")
ggplot(df2, aes(duration, slopes, col = color)) +
 geom_point(size = 3) +
 scale_color_gradient(low = "blue", high = "green")

产生以下两张图片

在此处输入图像描述

在此处输入图像描述

相反,我希望能够将它们集成在一个图中,一个红色和黑色的条形图和另一个蓝色和绿色的条形图。

标签: rggplot2

解决方案


是的,如果您使用该ggnewscale软件包,您可以:

a <- sample(nrow(iris), 75)

df1 <- iris[a,]
df2 <- iris[-a,]

library(ggnewscale)

ggplot(mapping = aes(Sepal.Width, Sepal.Length)) +
  geom_point(data = df1, aes(colour = Petal.Length)) +
  scale_colour_gradientn(colours = c("red", "black")) +
  # Important: define a colour/fill scale before calling a new_scale_* function
  new_scale_colour() +
  geom_point(data = df2, aes(colour = Petal.Width)) +
  scale_colour_gradientn(colours = c("blue", "white"))

在此处输入图像描述

替代方案是中继器包,或来自ggh4xscale_colour_multi的/ (完全免责声明:我写了 ggh4x)。scale_listed

编辑:以下是替代方案:

library(ggh4x)

# ggh4x scale_colour_multi (for gradientn-like scales)
ggplot(mapping = aes(Sepal.Width, Sepal.Length)) +
  geom_point(data = df1, aes(length = Petal.Length)) +
  geom_point(data = df2, aes(width = Petal.Width)) +
  scale_colour_multi(colours = list(c("red", "black"), c("blue", "white")),
                     aesthetics = c("length", "width"))

# ggh4x scale_listed (for any non-position scale (in theory))
ggplot(mapping = aes(Sepal.Width, Sepal.Length)) +
  geom_point(data = df1, aes(length = Petal.Length)) +
  geom_point(data = df2, aes(width = Petal.Width)) +
  scale_listed(list(
    scale_colour_gradientn(colours = c("red", "black"), aesthetics = "length"),
    scale_colour_gradientn(colours = c("blue", "white"), aesthetics = "width")
  ), replaces = c("colour", "colour"))


library(relayer)

# relayer
ggplot(mapping = aes(Sepal.Width, Sepal.Length)) +
  rename_geom_aes(geom_point(data = df1, aes(length = Petal.Length)), 
                  new_aes = c("colour" = "length")) +
  rename_geom_aes(geom_point(data = df2, aes(width = Petal.Width)),
                  new_aes = c("colour" = "width")) +
  scale_colour_gradientn(colours = c("red", "black"), aesthetics = "length", 
                         guide = guide_colourbar(available_aes = "length")) +
  scale_colour_gradientn(colours = c("blue", "white"), aesthetics = "width", 
                         guide = guide_colourbar(available_aes = "width"))

所有替代方案都会对未知的美学提出警告,但这对于生成的情节无关紧要。产生这个警告的只是 ggplot 函数中的一行代码,如果不重新编码每个包装器,或者像 ggnewscale 所做的那样,重命名旧美学而不是提供新美学,layer()就无法绕过这个问题。geom这些情节看起来几乎相同,所以我想我不必再发布它们了。


推荐阅读