ggplot2多个连续变量绘图

时间:2016-11-14 19:07:34

标签: r ggplot2 geom-bar facet-grid

我有一个如下所示的数据集:

  Distance  Mean    SD Median    VI Vegetation.Index       Direction  X X.1 X.2 X.3
1      10m 0.525 0.082  0.530  NDVI             NDVI Whole Landscape NA  NA  NA  NA
2      25m 0.517 0.085  0.523  NDVI             NDVI Whole Landscape NA  NA  NA  NA
3      50m 0.509 0.086  0.514  NDVI             NDVI Whole Landscape NA  NA  NA  NA
4     100m 0.494 0.090  0.497  NDVI             NDVI Whole Landscape NA  NA  NA  NA
5      10m 0.545 0.076  0.551 NDVIe             NDVI            East NA  NA  NA  NA
6      25m 0.542 0.078  0.549 NDVIe             NDVI            East NA  NA  NA  NA


> dput(droplevels(head(data)))
structure(list(Distance = structure(c(2L, 3L, 4L, 1L, 2L, 3L), .Label = c("100m", 
"10m", "25m", "50m"), class = "factor"), Mean = c(0.525, 0.517, 
0.509, 0.494, 0.545, 0.542), SD = c(0.082, 0.085, 0.086, 0.09, 
0.076, 0.078), Median = c(0.53, 0.523, 0.514, 0.497, 0.551, 0.549
), VI = structure(c(1L, 1L, 1L, 1L, 2L, 2L), .Label = c("NDVI", 
"NDVIe"), class = "factor"), Vegetation.Index = structure(c(1L, 
1L, 1L, 1L, 1L, 1L), .Label = "NDVI", class = "factor"), Direction = structure(c(2L, 
2L, 2L, 2L, 1L, 1L), .Label = c("East", "Whole Landscape"), class = "factor"), 
X = c(NA, NA, NA, NA, NA, NA), X.1 = c(NA, NA, NA, NA, NA, 
NA), X.2 = c(NA, NA, NA, NA, NA, NA), X.3 = c(NA, NA, NA, 
NA, NA, NA)), .Names = c("Distance", "Mean", "SD", "Median", 
"VI", "Vegetation.Index", "Direction", "X", "X.1", "X.2", "X.3"
), row.names = c(NA, 6L), class = "data.frame")

我想创建一个条形图小平面网格,其中x轴上的分类变量(距离),y轴上的连续变量(植被指数)和每个条形图的两个条形(平均和中位植被指数值) 。酒吧通过方向'和植被指数'。

我用一种措施(平均值)完成了这项工作,如下图所示。

enter image description here

以下是我现在的代码:

 p = ggplot(data,aes(x=Distance,y=Mean,fill=Distance)) + geom_bar(stat =
    'identity',position='dodge')+ facet_grid(Direction~Vegetation.Index)+ 
    coord_cartesian(ylim=c(0.2,0.95)) + geom_errorbar(data = data,
    aes(ymin=Mean-SD,ymax=Mean+SD),width=0.5)

但是我也希望旁边有一个中位数吧。

Like this但是对于构面网格中的所有条形图。

我找到了一些想要做这个或类似事情的人,发现它们非常有用:

This

Or this

但是,我的数据看起来与他们的数据非常不同(我认为)并且以任何方式改变它会弄乱我已经拥有的数据。根据我的理解,我必须使用group =' Mean + Median'。

1 个答案:

答案 0 :(得分:2)

使用您的示例数据,我们首先将其转换为长格式。我在这里使用tidyr::gather,但reshape2::melt(或data.table::melt)的工作方式类似。

library(tidyr)
dfl = gather(df, key = measure, value = value, Mean, Median)

dodge_width = 0.8
ggplot(dfl,
       aes(x = measure, y = value, fill = Distance, group = Distance)) +
    geom_bar(stat = 'identity',
             position = position_dodge(dodge_width),
             width = dodge_width) +
    facet_grid(Direction ~ Vegetation.Index) + 
    coord_cartesian(ylim = c(0.2, 0.95)) + 
    geom_errorbar(
        aes(ymin = value - SD, ymax = value + SD),
        width=0.5,
        position = position_dodge(dodge_width)
    )

enter image description here