如何将两种不同比例的颜色渐变与 ggplot 合并

Mar*_*ark 1 r ggplot2

通过使用 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")
Run Code Online (Sandbox Code Playgroud)

产生以下两张图片

在此处输入图片说明

在此处输入图片说明

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

teu*_*and 7

是的,如果您使用该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"))
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

替代方案是relayer包,或scale_colour_multi/scale_listedggh4x(全免责声明:我写ggh4x)。

编辑:以下是替代方案:

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"))
Run Code Online (Sandbox Code Playgroud)

所有替代方案都给出了关于未知美学的警告,但这对结果图无关紧要。它只是 ggplotlayer()函数中的一行代码,它产生了这个警告,你不能在不重新编码每个geom包装器的情况下解决这个问题,或者像 ggnewscale 那样,重命名旧的美学而不是提供新的美学。这些情节看起来几乎相同,所以我想我不必再次发布它们。