2017-06-15 119 views
0

我正在創建一個點的大小與給定變量的值成比例的情節,然後我平方以增加點之間大小的差異...ggplot2 geom_point圖例大小映射到一個變量時

# Using example from https://www3.nd.edu/~steve/computing_with_data/11_geom_examples/ggplot_examples.html # 

library(ggplot2) 
str(mtcars) 

p <- ggplot(data = mtcars, aes(x = wt, mpg)) 
p + geom_point(aes(size = (qsec^2))) 

enter image description here

從所得曲線圖,有沒有指定要在圖例中示出的點的大小和爲了體現原始值以及不平方改變圖例標籤的方式這些值? (如在圖上手動編輯)

回答

1

使用scale_size修改圖例。通過設置breakslabels,您可以生成所需的圖形。這裏有兩個例子。

示例1:構建比例以顯示mtcars$qsec的五個數字摘要並顯示原始單位中的標籤。

library(ggplot2) 

ggplot(mtcars, aes(x = wt, y = mpg)) + 
    geom_point(mapping = aes(size = qsec^2)) + 
    scale_size(name = "qsec", 
      breaks = fivenum(mtcars$qsec)^2, 
      labels = fivenum(mtcars$qsec)) 

enter image description here

實施例2:顯示圖例與qsec^2expression包裝將讓你格式化標籤太好看。

ggplot(mtcars, aes(x = wt, y = mpg)) + 
    geom_point(mapping = aes(size = qsec^2)) + 
    scale_size(name = expression(qsec^2), 
      breaks = c(15, 17, 19, 21)^2, 
      labels = expression(15^2, 17^2, 19^2, 21^2)) 

enter image description here