2015-04-17 47 views
6

r添加一個標籤用於與圖例的垂直線3.1.2/ggplot2_1.0.0/Windows7的如何GGPLOT2

一個如何添加2條垂直線與傳說在沒有他們改變線型多面圖?在下面的例子中,我不能讓傳說出現,因爲我會想象它們來自我正在寫的代碼(兩條實線和一個正確的傳說)。重複的例子:

library(ggplot2) 
library(plyr) 
library(e1071) 

set.seed(89) 
pm <- data.frame(pm10=rnorm(400, 150, 50), estacion=gl(4,100, labels = c('sur', 'norte', 'este', 'oeste'))) # data 
curtosis <- ddply(pm, .(estacion), function(val) sprintf("curtosis==%.2f", kurtosis(val$pm10))) 
asimetria <- ddply(pm, .(estacion), function(val) sprintf("asimetría==%.2f", skewness(val$pm10))) 

p1 <- ggplot(data=pm, aes(x=pm10, y=..density..)) + 
    geom_histogram(bin=15, fill='#deebf7', colour='#bdbdbd')+ 
    geom_density(size=1, colour='#cccccc')+ 
    geom_vline(data=aggregate(pm[1], pm[2], quantile, .8), mapping=aes(xintercept=pm10, linetype='percentil .8'), size=1, colour='#dfc27d', show_guide = T)+ 
    geom_vline(data=aggregate(pm[1], pm[2], median), mapping=aes(xintercept=pm10, linetype='mediana'), size=1, colour='#80cdc1', show_guide = T)+ 
    geom_text(data=curtosis, aes(x=350, y=.010, label=V1), size=3, parse=T)+ 
    geom_text(data=asimetria, aes(x=350, y=.008, label=V1), size=3, parse=T)+ 
    guides(linetype=guide_legend(override.aes=list(colour = c("#dfc27d","#80cdc1"))))+ 
    xlim(0,500)+ 
    facet_wrap(~ estacion, ncol=2) 

print(p1) 

enter image description here

我想將行作爲固體(顏色是確定)和傳奇的標題說:「Medida德tendencia」。

回答

5

與您的想法相似的主要想法ggplot是將數據準備與實際繪圖分開。在數據準備步驟中,您可以根據所考慮的繪圖概念來組織數據。

在你的情況,這意味着預計算的統計有問題:

df_vline <- rbind(
    aggregate(pm[1], pm[2], quantile, .8), 
    aggregate(pm[1], pm[2], median) 
) 
df_vline$stat <- rep(c("percentil .8", "mediana"), each = nrow(df_vline)/2) 

,然後映射方案是非常簡單的,所以你不必去想傳奇的手工覆蓋。

ggplot(data=pm, aes(x=pm10, y=..density..)) + 
    geom_histogram(bin=15, fill='#deebf7', colour='#bdbdbd')+ 
    geom_density(size=1, colour='#cccccc')+ 
    geom_vline(data=df_vline, mapping=aes(xintercept=pm10, colour = stat), 
      linetype = 1, size=1, show_guide = T)+ 
    geom_text(data=curtosis, aes(x=350, y=.010, label=V1), size=3, parse=T)+ 
    geom_text(data=asimetria, aes(x=350, y=.008, label=V1), size=3, parse=T)+ 
    scale_colour_manual(values = c("#dfc27d","#80cdc1"), name = "Medida de tendencia")+ 
    xlim(0,500)+ 
    facet_wrap(~ estacion, ncol=2) 

enter image description here

(尼斯情節,順便說一句。)