根据尺寸将图例添加到ggplot2 geom_tile图中 [英] Adding a legend to a ggplot2 geom_tile plot based on size

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

问题描述

我正在使用geom_tile在ggplot2中创建波动图,并希望添加尺寸图例.我不知道该怎么做.这是MWE:

I am creating fluctuation diagrams in ggplot2 using geom_tile, and would like to add a legend for size. I am at a loss as to how to do so. Here is a MWE:

library(dplyr)
library(ggplot2)

# create data frame of total number of passengers in each Sex-Age group

df <- data.frame(Titanic) %>% group_by(Sex, Age) %>%
    summarise (freq = sum(Freq))

# calculate the lengths of the sides of the tiles so the largest has
# area = 1 and the others are smaller proportional to frequency

df$tileside <- sqrt(df$freq / max(df$freq))

df

## Source: local data frame [4 x 4]
## Groups: Sex [?]
## 
##      Sex    Age  freq  tileside
##   (fctr) (fctr) (dbl)     (dbl)
## 1   Male  Child    64 0.1959396
## 2   Male  Adult  1667 1.0000000
## 3 Female  Child    45 0.1643003
## 4 Female  Adult   425 0.5049248
# using geom_tile, no size legend

ggplot(df, aes(x = Sex, y = Age, 
               height = tileside, width = tileside)) +
    geom_tile() + coord_fixed (ratio = 1)

我应该提到一种替代方法是使用geom_point而不是geom_tile(请参阅此帖子:

I should mention that one alternative would be to use geom_point instead of geom_tile (see this post: https://stats.stackexchange.com/questions/56322/graph-for-relationship-between-two-ordinal-variables/56357#56357)

这是这种方法的MWE:

Here is a MWE of this approach:

ggplot(df, aes(x = Sex, y = Age, size = freq)) +
    geom_point(shape = 15) + coord_fixed (ratio = 1)

问题在于正方形太小,如果我用scale_size()重新缩放它们,我将失去波动图的最重要特征-正方形的面积与频率成正比. (我不确定即使不重新缩放也能满足此条件-很难说出面积的计算方式.)

The problem is that the squares are too small, and if I rescale them, with scale_size(), I lose the most important feature of the fluctation diagram–that the area of the squares is proportional to frequency. (I’m not sure if this condition is met even without rescaling – it’s hard to tell how the area is calculated).

非常感谢您的帮助.

推荐答案

对于大小问题,可以使用scale_size_area.我也添加了颜色.

As for the size issue, you can use scale_size_area. I added color as well.

ggplot(df, aes(x = Sex, y = Age, size = freq, color = freq)) +
  geom_point(shape = 15)  + coord_fixed (ratio = 1) + 
  scale_size_area(max_size = 20) +
  scale_color_gradient(high="red", low="black", guide = "legend") 

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

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