上面的ggplot2 版本的一个小变化,使用ggalt 中的geom_lollipop 并使用cowplot 作为漂亮的背景主题。将图形高度设置为漂亮且小且宽度较长很重要(在我的 RMarkdown 块中,我有 fig.height = 3 和 fig.width = 10)
我还使用了来自this question 的(稍作修改)函数,它有助于移动 x 轴(修改后的函数使用 annotate 而不是 geom_hline。这允许我添加一个箭头)。
抱歉,为简洁起见,我在这里使用了自己的数据。我得回去工作了!!
library(ggplot2)
library(dplyr)
library(ggalt)
library(cowplot)
library(tibble)
library(lubridate)
#Create data to plot
data <- tribble( ~start_date, ~event, ~displ,
ymd(20160201), "Initial meeting with Renfrewshire", 1,
ymd(20160430), "UBDC RAC submission", 0.7,
ymd(20160524), "College Ethics Approval", 0.5,
ymd(20160601), "UBDC RAC approval", -0.5,
ymd(20161101), "Agreeement in Principal", 0.3,
ymd(20170906), "DSA signed", 0.5,
ymd(20170921), "Data transferred", -0.5,
ymd(20180221), "Analysis complete", 0.5)
#Function to shift x-axis to 0 adapted from link shown above
shift_axis <- function(p, xmin, xmax, y=0){
g <- ggplotGrob(p)
dummy <- data.frame(y=y)
ax <- g[["grobs"]][g$layout$name == "axis-b"][[1]]
p + annotation_custom(grid::grobTree(ax, vp = grid::viewport(y=1, height=sum(ax$height))),
ymax=y, ymin=y) +
annotate("segment", y = 0, yend = 0, x = xmin, xend = xmax,
arrow = arrow(length = unit(0.1, "inches"))) +
theme(axis.text.x = element_blank(),
axis.ticks.x=element_blank())
}
#Conditionally set whether text will be above or below the point
vjust = ifelse(data$displ > 0, -1, 1.5)
#plot
p1 <- data %>%
ggplot(aes(start_date, displ)) +
geom_lollipop(point.size = 1) +
geom_text(aes(x = start_date, y = displ, label = event), data = data,
hjust = 0, vjust = vjust, size = 2.5) +
theme(axis.title = element_blank(),
axis.text.y = element_blank(),
axis.ticks.y = element_blank(),
axis.line = element_blank(),
axis.text.x = element_text(size = 8)) +
expand_limits(x = c(ymd(20151201), ymd(20180501)), y = 1.2) +
scale_x_date(breaks = scales::pretty_breaks(n = 9))
#and run the function from above
timeline <- shift_axis(p1, ymd(20151201), ymd(20180501))
生产....