在同一日期有多个ID的条形图

时间:2013-10-28 15:31:33

标签: r ggplot2 bar-chart

编辑:这是数据:

date<-c("20130107", "20130109", "20130111", "20130111", "20130113", "20130114", "20130114", "20130122", "20130125", "20130125", "20130128")
ID<-c("Blue","Red","Red","Red","Red","Red","White","Green","Black","Purple","Purple")
date_ID<-c("20130107 Blue", "20130109 Red", "20130111 Red", "20130111 Red", "20130113 Red", "20130114 Red", "20130114 White", "20130122 Green", "20130125 Black", "20130125 Purple", "20130128 Purple")
perc_yes<-c(-0.10394265, -1.00000000, -1.00000000, -1.00000000, -1.00000000, -1.00000000, -0.40425532, -0.09297913, -1.00000000, -0.17864924, -0.12353401)
perc_no<-c(0.8960573, 0.0000000, 0.0000000, 0.0000000, 0.0000000, 0.0000000, 0.5957447, 0.9070209, 0.0000000, 0.8213508, 0.8764660)
data<-data.frame(date,ID,date_ID,perc_yes,perc_no)

我的数据框如下:

    date        ID          date_ID     perc_yes    perc_no
1   20130107    Blue    20130107 Blue   -0.10394265 0.8960573
2   20130109    Red     20130109 Red    -1.00000000 0.0000000
3   20130111    Red     20130111 Red    -1.00000000 0.0000000
4   20130111    Red     20130111 Red    -1.00000000 0.0000000
5   20130113    Red     20130113 Red    -1.00000000 0.0000000
6   20130114    Red     20130114 Red    -1.00000000 0.0000000
7   20130114    White   20130114 White  -0.40425532 0.5957447
8   20130122    Green   20130122 Green  -0.09297913 0.9070209
9   20130125    Black   20130125 Black  -1.00000000 0.0000000
10  20130125    Purple  20130125 Purple -0.17864924 0.8213508
11  20130128    Purple  20130128 Purple -0.12353401 0.8764660

它列出了日期,ID,然后是日期和ID,它们是如何分组的,百分比是和百分比否。我想按时间顺序按日期和ID制作条形图,如果条形图在同一天但不同的ID,则这些条形图被组合在一起。是的百分比是负数,因为我希望它们直接落在百分比no的下方负y方向。

我尝试过barplot没有成功,因为有多个数据点和堆叠。有没有办法在绘图函数中添加多个条形图点,如line()?我如何绘制数据?使用ggplot会更好吗(我有点不熟悉)?

1 个答案:

答案 0 :(得分:0)

我猜ggplot2可能更灵活,但我不知道。也许以下 - 仅使用barplot - 可能会有所帮助:

#turn `data$date` to actual date
data$date <- as.Date(data$date, format = "%Y%m%d")

#sort by date
data <- data[order(data$date),]

#`space` argument of barplot; 
#to group together same dates based on their difference in days
#see ?diff.Date
space. <- diff(data$date) + 0.5
space. <- c(space.[1], space.)

#plot no's
barplot(data$perc_no, names.arg = paste0(data$date, "\n", data$ID), cex.names = 0.7, 
        ylim = c(range(c(data$perc_yes, data$perc_no))),
        col = rgb(1,0,0,1/3), space = space.)

#plot yes'
barplot(data$perc_yes, col = rgb(0,0,1,1/3), , space = space., add = T)

情节如下:

barplot