R 基于大小向ggplot2 geom_平铺图添加图例
我正在使用R 基于大小向ggplot2 geom_平铺图添加图例,r,ggplot2,R,Ggplot2,我正在使用geom_tile在ggplot2中创建波动图,并希望为大小添加图例。我不知道该怎么做。这里是一个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 = s
geom_tile
在ggplot2中创建波动图,并希望为大小添加图例。我不知道该怎么做。这里是一个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)
问题是这些方块太小,如果我用scale_size()重新缩放它们,我就失去了fluctation图最重要的特征——方块的面积与频率成正比。(即使不重新缩放,我也不确定是否满足此条件——很难说面积是如何计算的)
非常感谢您的帮助。关于尺寸问题,您可以使用
缩放尺寸面积。我还加了颜色
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")
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")