2016-05-22 16 views
2

geom_tileを使用してggplot2で変動図を作成しています。サイズの凡例を追加したいと思います。私はそうする方法を失っている。ここMWEです:サイズに基づいてggplot2 geom_tileプロットに凡例を追加

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) 

enter image description here

私は1つの代替ではなくgeom_tileのgeom_pointを用いることであろうことを言及する必要があります(この記事を参照してください。https://stats.stackexchange.com/questions/56322/graph-for-relationship-between-two-ordinal-variables/56357#56357

は、ここでは、このアプローチのMWEは以下のとおりです。

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

enter image description here

問題は四角形が小さすぎることです。私がscale_size()を使ってスケールを変更すると、四角形の面積が周波数に比例するという変動図の最も重要な特徴が失われます。 (この条件が再スケーリングされなくても満たされているかどうかはわかりません。領域の計算方法は分かりません)。

ご協力いただきありがとうございます。

答えて

2

サイズの問題については、scale_size_areaを使用できます。色も付け加えました。

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

enter image description here

関連する問題