新增水平和垂直線以進行繪圖

為所有分類變數新增一條公共水平線

# sample data
df <- data.frame(x=('A', 'B'), y = c(3, 4))

p1 <- ggplot(df, aes(x=x, y=y)) 
        + geom_bar(position = "dodge", stat = 'identity') 
        + theme_bw()

p1 + geom_hline(aes(yintercept=5), colour="#990000", linetype="dashed")

StackOverflow 文件

為每個分類變數新增一條水平線

# sample data
df <- data.frame(x=('A', 'B'), y = c(3, 4))

# add horizontal levels for drawing lines
df$hval <- df$y + 2

p1 <- ggplot(df, aes(x=x, y=y)) 
        + geom_bar(position = "dodge", stat = 'identity') 
        + theme_bw()

p1 + geom_errorbar(aes(y=hval, ymax=hval, ymin=hval), colour="#990000", width=0.75)

StackOverflow 文件

在分組條上新增水平線

# sample data
df <- data.frame(x = rep(c('A', 'B'), times=2), 
             group = rep(c('G1', 'G2'), each=2), 
             y = c(3, 4, 5, 6), 
             hval = c(5, 6, 7, 8))

p1 <- ggplot(df, aes(x=x, y=y, fill=group)) 
        + geom_bar(position="dodge", stat="identity")

p1 + geom_errorbar(aes(y=hval, ymax=hval, ymin=hval), 
               colour="#990000", 
               position = "dodge", 
               linetype = "dashed")

StackOverflow 文件

新增垂直線

# sample data
df <- data.frame(group=rep(c('A', 'B'), each=20), 
                 x = rnorm(40, 5, 2), 
                 y = rnorm(40, 10, 2))

p1 <-  ggplot(df, aes(x=x, y=y, colour=group)) + geom_point()

p1 + geom_vline(aes(xintercept=5), color="#990000", linetype="dashed")

StackOverflow 文件