将多个图例添加到ggplot geom_tile [英] Add multiple legends to ggplot geom_tile

查看:57
本文介绍了将多个图例添加到ggplot geom_tile的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用ggplot创建热图样式图,并想添加第二个图例,并以不同的方式缩放数据.我想知道是否有简单的方法可以做到这一点.

我不认为这是其他多个传说"问题的重复,例如

对缩放后的z进行相同操作可以得出相同的图,但对于缩放后的图例:

  ggplot(example_data,aes(x = x,y = y,fill = z_rescale))+geom_tile()+scale_fill_gradient(low ="blue",high ="red")+scale_x_continuous(expand = c(0,0))+scale_y_continuous(expand = c(0,0)) 

但是我想做的是,用一张图显示两个不同的图例,看起来像这样的模型:

现在,我想可以通过创建两个图,找到其中一个代表图例的grob并将其巧妙地添加到第二个图中来实现这一点……但是,我有一种更简单的方法吗?我可以俯瞰吗?

非常感谢!

解决方案

请添加代码

  aes(color = z_rescale)+scale_color_gradient(low ="blue",high ="red")+ 

geom_tile()行之后,您将获得所需的

I'm using ggplot to create a heat-map style plot, and would like to add a second legend with the data scaled a different way. I'm wondering if there is a simple way to do this.

I do not believe that this is a duplicate of other "multiple legends" questions e.g. Multiple legends for a ggplot in R as crucially I want to add extra legends for the same aesthetic - i.e. one aesthetic mapping, two legends.

Example code

# Create a dataframe with some dummy data

x <- c()
y <- c()

for(i in 1:100){
  for(j in 1:100){

    x <- c(x, i)
    y <- c(y, j)
  }
}

example_data <- data.frame(x, y)
example_data$z <- example_data$x*example_data$y
example_data$z_rescale <- example_data$z*0.5

Now we've got some data that I'd like to plot as a heatmap with "z" as a colour gradient.

ggplot(example_data, aes(x = x, y = y, fill = z)) + 
  geom_tile() +
  scale_fill_gradient(low = "blue", high = "red") +
  scale_x_continuous(expand = c(0, 0)) +
  scale_y_continuous(expand = c(0, 0))

Doing the same with the rescaled z gives an identical plot, but with the rescaled legend:

ggplot(example_data, aes(x = x, y = y, fill = z_rescale)) + 
  geom_tile() +
  scale_fill_gradient(low = "blue", high = "red") +
  scale_x_continuous(expand = c(0, 0)) +
  scale_y_continuous(expand = c(0, 0))

What I'd like to do however is have a single plot showing the two different legends, which would look something like this mock-up:

Now, I imagine this would be possible by creating two plots, finding the grob that represents the legend in one of the plots and cunningly adding it to the second plot... however, is there a much simpler way that I'm overlooking?

Many thanks!

解决方案

Please add the code

aes(color = z_rescale) +
scale_color_gradient(low = "blue", high = "red") +

after geom_tile() line and you will get the desired

这篇关于将多个图例添加到ggplot geom_tile的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆