浮动条形图,其中日期作为r中的绘制值 [英] Floating bar chart with dates as the plotted values in r

查看:79
本文介绍了浮动条形图,其中日期作为r中的绘制值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想绘制一个特定对象处于活动状态的日期范围,如下所示:





此示例摘自



增加 lwd 可获得更粗的线条。如果要对其进行更多控制,请考虑以相同的方式使用 rect


I want to plot the range of dates where a particular object is "active", as shown below:

This example is taken from Wikipedia. Here is the data:

df1 <- data.frame(
  name = c("Eazy-E", "DJ Yella", "Dr. Dre",
    "Ice Cube", "Arabian Prince", "MC Ren"),
  from = as.Date(c("01/01/1986", "01/01/1986", "01/01/1986",
    "01/01/1986", "01/01/1986","02/01/1988"), "%m/%d/%Y"),
  to = as.Date(c("08/01/1991", "08/01/1991", "07/01/1991",
    "12/01/1989", "07/01/1988", "08/01/1991"),"%m/%d/%Y"))

df1
            name       from         to
1         Eazy-E 1986-01-01 1991-08-01
2       DJ Yella 1986-01-01 1991-08-01
3        Dr. Dre 1986-01-01 1991-07-01
4       Ice Cube 1986-01-01 1989-12-01
5 Arabian Prince 1986-01-01 1988-07-01
6         MC Ren 1988-02-01 1991-08-01

I can't figure out how to:

  1. Plot the value of dates
  2. Make floating bar charts

Thanks for any input.

解决方案

It doesn't appear to be a bar chart per se, more of a collection of lines or rectangles. As such, this can be tackled with lines(), rect(), or even polygon(). I'll show the first, I hope you'll get the gist.

Your data:

dat <- structure(list(name = c("Eazy-E", "DJ Yella", "Dr. Dre", "Ice Cube", "Arabian Prince", "MC Ren"),
                      from = c("1986-01-01", "1986-01-01", "1986-01-01", "1986-01-01", "1986-01-01", "1988-02-01"),
                      to = c("1991-08-01", "1991-08-01", "1991-07-01", "1989-12-01", "1988-07-01", "1991-08-01")),
                 .Names = c("name", "from", "to"), row.names = c(NA, -6L), class = "data.frame")
dat$from <- as.POSIXct(dat$from)
dat$to <- as.POSIXct(dat$to)
dat
##             name       from         to
## 1         Eazy-E 1986-01-01 1991-08-01
## 2       DJ Yella 1986-01-01 1991-08-01
## 3        Dr. Dre 1986-01-01 1991-07-01
## 4       Ice Cube 1986-01-01 1989-12-01
## 5 Arabian Prince 1986-01-01 1988-07-01
## 6         MC Ren 1988-02-01 1991-08-01

One solution:

par(mar=c(2,8,0,0) + 0.1)
plot(0, type='n', xlim=range(c(dat$from, dat$to)), ylim=c(1, nrow(dat)),
     main='', xlab='', ylab='', xaxt='n', yaxt='n')
years <- seq.POSIXt(min(dat$from), max(dat$to), by='1 year')
abline(v=years, lty=3, col='gray')
axis(1, at=years, labels=format(years, '%Y'))
axis(2, at=1:nrow(dat), labels=rev(dat$name), las=2)
lines(x=as.POSIXct(c(apply(dat[,c('from','to')], 1, c, NA))),
      y=rep(nrow(dat):1, each=3),
      lwd=5)

Increase lwd to get thicker lines. If you want more control over it, consider using rect in the same fashion.

这篇关于浮动条形图,其中日期作为r中的绘制值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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