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

时间:2019-10-13 09:52:40

标签: r ggplot2

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

def fun(count=0):
    if count < 5:
        print(count)
        count+=1
        fun(count)

fun()

产生以下两张图片

enter image description here

enter image description here

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

1 个答案:

答案 0 :(得分:4)

是的,如果您使用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"))

enter image description here

替代方案是relayer软件包,或者是ggnomics中的scale_colour_multi / scale_listed(完全免责声明:我写了ggnomics)。

编辑:以下是替代方法:

library(ggnomics)

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

# ggnomics 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的layer()函数中只有一行代码会产生此警告,如果不重新编码每个geom包装器,或者像ggnewscale一样,重命名旧的外观,就无法解决这个问题提供新的美学。这些图看起来都差不多,因此我认为不必再次发布它们。