如何在geom_ribbon上使用geom_pointranges生成单个图? (主要是显示数据点及其标准偏差)

时间:2017-10-02 14:28:48

标签: r ggplot2

我这里有两张图“PlotA”和“PlotB”,但是我想要一个组合图表,其中geom_pointranges显示点,geom_line显示行,geom_ribbon显示标准差。

water <- c(35,40,42,46,48,50)
depth <- c(1,2,3,4,5,6)
sd <- c(10,10,10,10,10,10)
dataA <- data.frame(depth, water, sd)

from <- c(0.5, 1.5, 2.5, 3.5, 4.5, 5.5)
to <- c(1.5, 2.5, 3.5, 4.5, 5.5, 6.5)
depth1 <- c(1,2,3,4,5,6)
water1 <- c(40,32,50,55,62,30)
dataB <- data.frame(from,to,depth1, water1)

# Load necessary packages

require(ggplot2)

# Plotting Started

#PlotA
ggplot(data=dataA, aes(x = water, y = depth), na.rm=T) +
geom_path(size=0.4, color="black")+
geom_pointrange(data=dataB, aes(water1, depth1, ymin=from, ymax=to),      size=0.1, color='black') +
scale_y_reverse(lim = c(10,0), breaks = seq(0,10,1)) +
theme_bw(12) +
scale_x_continuous(lim =c(0,100), breaks = seq(0,100,20))

#PlotB
ggplot() + geom_ribbon(data=dataA, aes(x=depth, y=water, ymin = water - sd,   ymax = water + sd), alpha=0.3, fill='grey12') + coord_flip() + 
scale_x_reverse(lim = c(10,0), breaks = seq(0,10,1)) + theme_bw(12) +
scale_y_continuous(lim =c(0,100), breaks = seq(0,100,20))

1 个答案:

答案 0 :(得分:1)

coord_flip很难在情节中使用。我强烈建议在没有它的情况下调试绘图,然后在最后一步添加它。

我认为这是你正在寻找的东西。如果没有,请更详细地描述您想要的结果。

ggplot(data = dataA, aes(x = depth, y = water)) +
    geom_ribbon(
        data = dataA,
        aes(
            x = depth,
            ymin = water - sd,
            ymax = water + sd
        ),
        alpha = 0.3,
        fill = 'grey12'
    ) +
    geom_path(size = 0.4, color = "black") +
    geom_point(
        data = dataB,
        aes(x = depth1, y = water1),
        size = 0.1,
        color = 'black'
    ) +
    geom_errorbarh(
        data = dataB,
        aes(
            x = depth1,
            xmin = from,
            xmax = to,
            y = water1
        ),
        size = 0.1,
        height = 0
    ) +
    theme_bw(12) +
    scale_x_reverse(lim = c(10, 0), breaks = seq(0, 10, 1)) +
    scale_y_continuous(lim = c(0, 100), breaks = seq(0, 100, 20)) +
    coord_flip()

enter image description here