【问题标题】:How to add a label for a vertical line with legend in ggplot2如何在ggplot2中为带有图例的垂直线添加标签
【发布时间】:2015-04-17 22:27:06
【问题描述】:

R 3.1.2/ggplot2_1.0.0/Windows7

如何在多面图中添加 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)

我希望线条是实心的(颜色没问题),并且图例的标题是:“Medida de tentencia”。

【问题讨论】:

    标签: r ggplot2 legend facet


    【解决方案1】:

    像你这样相当复杂的ggplots 的主要思想是将数据准备与实际绘图分开。在数据准备步骤中,您可以根据您想到的绘图概念来组织数据。

    在您的情况下,这意味着预先计算有问题的统计数据:

    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) 
    

    (顺便说一句,情节不错。)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多