如何在ggplot中添加带有标签的水平虚线

时间:2019-07-24 07:36:59

标签: r ggplot2

我已经画了一条线图。我在情节上添加了一条水平线。如何拍摄水平线红色虚线?

# Sample Data 

library(tidyverse)
Month= c("Jan","Feb","Mar","Apr","May","Jun")
a = c(11,10,9,8,4,8)

test= data_frame(Month,a) 
test$cum_total <- cumsum(test$a)

test$Month <- factor(test$Month, month.abb)

# ggplot

ggplot(data=test, aes(x=Month, y=cum_total, group=1)) +
  geom_line()+
  geom_point()+
  geom_hline(yintercept=40)+
  annotate("text", x = "Feb", y = 40, label = "Previous Level", vjust = -0.5)

1 个答案:

答案 0 :(得分:0)

要使水平线变为红色并虚线,应在geom_hline函数调用中包含以下参数:

linetype = 'dotted', col = 'red'

# Sample Data 

library(tidyverse)
Month= c("Jan","Feb","Mar","Apr","May","Jun")
a = c(11,10,9,8,4,8)

test= data_frame(Month,a) 
test$cum_total <- cumsum(test$a)

test$Month <- factor(test$Month, month.abb)

# ggplot

ggplot(data=test, aes(x=Month, y=cum_total, group=1)) +
  geom_line()+
  geom_point()+
  geom_hline(yintercept=40, linetype='dotted', col = 'red')+
  annotate("text", x = "Feb", y = 40, label = "Previous Level", vjust = -0.5)

enter image description here