x轴上具有年月的GGPlot [英] Ggplot with yearmonth in x-axis

查看:23
本文介绍了x轴上具有年月的GGPlot的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据集,其中包含个人随时间在哪里工作的信息,其中时间定义为年/月(在我的数据集中显示为数字值YYYYMM)。我运行了一个GGPlot,以可视化个人在给定工作场所停留的时间,以及他们是如何四处走动的。我使用position_dodge使其在同一个月内同一人在多个地方工作时可见。

在下面的简单示例中:

  • A个人从2012年1月(即201201)到2012年12月在岗位1工作
  • 个人B从2012年1月到2012年6月在地点2工作,然后从2012年7月到2012年11月切换到地点2
  • 个人C从2012年1月至2012年4月在地点1工作,从2012年2月至2012年6月在地点2工作
  • 个人D仅在2012年1月/日期间在1号位置工作

我的问题与如何使用时间间隔有关。在我的数据集中,时间段变量指的是整个月。例如,个人A从2012年1月1日到2012年12月31日在工作场所1实际工作,个人D从2012年1月1日到2012年1月31日在工作场所1工作。

# individual A
a_id <- c(rep('A',12))
a_period <- c(seq(201201, 201212))
a_workplace <-c(rep(1,12))

# individual B
b_id <- c(rep('B',11))
b_period <- c(seq(201201,201206), seq(201207,201211))
b_workplace <-c(rep(1,6), rep(2,5))

# individual C
c_id <- c(rep('C',9))
c_period <- c(seq(201201,201204), seq(201202,201206))
c_workplace <-c(rep(1,4), rep(2,5))

# individual D
d_id <- c(rep('D',1))
d_period <- c(seq(201201,201201))
d_workplace <-c(rep(1,1))

# final data frame
id <- c(a_id, b_id, c_id, d_id)
period <- c(a_period, b_period, c_period, d_period)
workplace <- as.factor(c(a_workplace, b_workplace, c_workplace, d_workplace))
mydata <- data.frame(id, period, workplace)

ggplot(mydata, aes(x = id, y = period, color = workplace)) +
  geom_line(position = position_dodge(width = 0.1), size = 2) +
  scale_x_discrete(limits = rev) +
  scale_y_continuous(breaks = seq(201201, 201212, by = 1)) +
  coord_flip() +
  theme(axis.text.x = element_text(angle=45, hjust=1),
        legend.position   = c(.8, .2), 
        legend.direction  = "vertical",
        legend.background = element_rect(linetype = "solid", colour = "black"), 
        panel.background  = element_rect(fill = "grey97")) +
  labs(y = "time", title = "Work affiliation")

上面的gggraph将年/月视为单个时间点。例如,它没有显示个人D的工作历史记录。如何将个人-工作场所级别的每个连续序列视为从第一个月的第一天开始,并在连续序列的最后一个月的最后一天结束。我还希望将年/月变量从数字格式转换为日期格式,以简化操作。

PS:我在上面的段落中突出显示每个连续的序列,因为同一个人可能会在给定的地方工作几个月,离开一段时间,然后稍后再回到这个相同的工作场所工作。在这些情况下,应分别考虑此给定工作场所中个人工作的两个时间间隔。

推荐答案

关于第二个问题有关数字到日期类型的转换,我得到了答案:

library(lubridate) # handling and conversion of datetype
lubridate::ymd() # turns your numeric into a date
as.Date() #turns your characterstring into date type which is by the way the 
#proper way you should handover timerelated data to ggplot

这对您的代码来说应该足够了:

mydata$period=lubridate::ymd(mydata[,2])

这篇关于x轴上具有年月的GGPlot的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆