使用ggplot2绘制时间线

发布于 2024-12-05 21:18:04 字数 545 浏览 2 评论 0原文

我有类似的数据

data = as.data.frame(  rbind(   c("1492", "Columbus sailed the ocean blue"),
                                c("1976", "Americans listened to Styx"),
                                c("2008", "financial meltdown. great.")
                                ))

,我想在 ggplot2 中构建一个图,它将显示时间箭头 aes(x=$V1) 和文本 aes(label =$V2)。听起来很简单,直到我尝试画它。

更新:我没有写它,但您需要执行 as.Date("1492", format="%Y") 才能正确重现。

注意:下面给出的解决方案仅处理在特定日期发生的事件,而不是具有“时期”或“时代”的时间线。

I have data like

data = as.data.frame(  rbind(   c("1492", "Columbus sailed the ocean blue"),
                                c("1976", "Americans listened to Styx"),
                                c("2008", "financial meltdown. great.")
                                ))

and I want to build a plot in ggplot2 that will display an arrow for time aes(x=$V1) and text for aes(label=$V2). It sounded pretty simple until I tried to draw it.

update: I didn't write it but you need to do as.Date("1492", format="%Y") to reproduce correctly.

NB: Solutions given below only deal with events that occur at a specific date -- not timelines with "periods" or "eras".

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

一笔一画续写前缘 2024-12-12 21:18:04

有时,最简单的图形是最难在 ggplot2 中创建的,但这是可能的(而且很漂亮)。

data =data.frame( V1=c(1492,1976,2008),V2=c("Columbus sailed the ocean blue","Americans listened to Styx","financial meltdown"),disloc=c(-1,1,-.5))
dev.new()
ggplot() +
    geom_segment(aes(x = V1,y = disloc,xend = V1),data=data,yend = 0) +
    geom_segment(aes(x = 900,y = 0,xend = 2050,yend = 0),data=data,arrow = arrow(length = unit(x = 0.2,units = 'cm'),type = 'closed')) +
    geom_text(aes(x = V1,y = disloc,label = V2),data=data,hjust = 1.0,vjust = 1.0,parse = FALSE) +
    geom_point(aes(x = V1,y = disloc),data=data) +
    scale_x_continuous(breaks = c(1492,1976,2008),labels = c("1492","1976","2008")) +
    theme_bw() +
    opts(axis.text.x = theme_text(size = 12.0,angle = 90.0),axis.text.y = theme_blank(),axis.ticks = theme_blank(),axis.title.x = theme_blank(),axis.title.y = theme_blank())

在此处输入图像描述

注意:该图形完全是在 演绎器

Sometimes the simplest graphics are the most difficult to create in ggplot2, but it is possible (and pretty).

data =data.frame( V1=c(1492,1976,2008),V2=c("Columbus sailed the ocean blue","Americans listened to Styx","financial meltdown"),disloc=c(-1,1,-.5))
dev.new()
ggplot() +
    geom_segment(aes(x = V1,y = disloc,xend = V1),data=data,yend = 0) +
    geom_segment(aes(x = 900,y = 0,xend = 2050,yend = 0),data=data,arrow = arrow(length = unit(x = 0.2,units = 'cm'),type = 'closed')) +
    geom_text(aes(x = V1,y = disloc,label = V2),data=data,hjust = 1.0,vjust = 1.0,parse = FALSE) +
    geom_point(aes(x = V1,y = disloc),data=data) +
    scale_x_continuous(breaks = c(1492,1976,2008),labels = c("1492","1976","2008")) +
    theme_bw() +
    opts(axis.text.x = theme_text(size = 12.0,angle = 90.0),axis.text.y = theme_blank(),axis.ticks = theme_blank(),axis.title.x = theme_blank(),axis.title.y = theme_blank())

enter image description here

Note: this graphic was produced entirely in the ggplot2 Plot Builder in Deducer

絕版丫頭 2024-12-12 21:18:04

上面的 ggplot2 版本有一点变化,使用了 ggalt 中的 geom_lollipop 并使用了 cowplot 来制作漂亮的背景主题。重要的是,将图形高度设置为漂亮且较小且宽度较长(在我的 RMarkdown 块中,我有 fig.height = 3fig.width = 10

我已经还使用了 这个问题有助于移动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))

产生....

我的论文项目之一的时间表

A little variation of the ggplot2 version above making use of geom_lollipop from ggalt and using cowplot for the nice background theme. Important to set the figure height as nice and small with a longer width (in my RMarkdown chunk I have fig.height = 3 and fig.width = 10)

I've also used a (slightly adapted) function from this question which helps move the x-axis (the adapted function uses annotate rather than geom_hline. This allows me to add an arrow).

Apologies, I have used my own data here for reasons of brevity. I need to get back to work!!

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))

Produces....

Timeline for one of my thesis projects

陌路黄昏 2024-12-12 21:18:04

这看起来还不错...
在此处输入图像描述

dislocations <- c(-1,1,-.5)
ggplot( data )
+ geom_text( aes(x = V1, y=dislocations, label = V2), position="jitter" )
+ geom_hline( yintercept=0, size=1, scale="date" )
+ geom_segment(  aes(x = V1, y=dislocations, xend=V1, yend=0, alpha=.7 ))

但它仍然缺少适当的“时间箭头”,背景看起来不正确,并且有标签y 轴上的值。

This looks kind of OK...
enter image description here

dislocations <- c(-1,1,-.5)
ggplot( data )
+ geom_text( aes(x = V1, y=dislocations, label = V2), position="jitter" )
+ geom_hline( yintercept=0, size=1, scale="date" )
+ geom_segment(  aes(x = V1, y=dislocations, xend=V1, yend=0, alpha=.7 ))

but it still lacks a proper "time arrow", the background doesn't look right, and it labels values on the y axis.

金橙橙 2024-12-12 21:18:04

对于 R 的基础图形来说,这似乎是更好的工作(实际上,这种东西可能更适合 Illustrator 或类似工具)。

dat = as.data.frame(rbind(c("1492", "Columbus sailed the ocean blue"),
                       c("1976", "Americans listened to Styx"),
                       c("2008", "Financial meltdown")))
dat$V1 <- as.Date(dat$V1,"%Y")
dat$val <- c(-1,1,-0.5)

plot(dat$V1,dislocations, type = "n",xaxt = "n",bty = "n", 
     xlab = "Time", ylab = "Dislocations")
u <- par("usr")
arrows(u[1], 0, u[2], 0, xpd = TRUE)
points(dat$V1,dat$val,pch = 20)
segments(dat$V1,c(0,0,0),dat$V1,dat$val)
text(x=dat$V1,y=dat$val,labels=dat$V2,pos=c(4,2,2))

产生如下内容:

在此处输入图像描述

This seems like a better job for R's base graphics (really, this kind of thing probably better fits with a tool like Illustrator or something of that ilk).

dat = as.data.frame(rbind(c("1492", "Columbus sailed the ocean blue"),
                       c("1976", "Americans listened to Styx"),
                       c("2008", "Financial meltdown")))
dat$V1 <- as.Date(dat$V1,"%Y")
dat$val <- c(-1,1,-0.5)

plot(dat$V1,dislocations, type = "n",xaxt = "n",bty = "n", 
     xlab = "Time", ylab = "Dislocations")
u <- par("usr")
arrows(u[1], 0, u[2], 0, xpd = TRUE)
points(dat$V1,dat$val,pch = 20)
segments(dat$V1,c(0,0,0),dat$V1,dat$val)
text(x=dat$V1,y=dat$val,labels=dat$V2,pos=c(4,2,2))

produces something like this:

enter image description here

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文