绘制二元系列的多个面板

Roo*_*ope 1 plot r time-series binary-data

我在数据框中有以下形式的二进制事件数据:

year   A   B   C   D
1990   0   0   1   0
1991   0   1   1   0
1992   0   0   0   1
1993   1   1   0   0
Run Code Online (Sandbox Code Playgroud)

总共可能有大约50个系列,大约25年.

我的目标是在一个图中显示所有系列,以可视化系列的聚合视图.

即我想在一个图中绘制所有数据的图形,因此对于每个列,将有一个单独的面板在彼此之上.每个面板可以是简单的直方图(即type="h")以可视化二进制数据.

除了最底部的面板之外,面板之间自然应该没有x轴标签和刻度等.

现在,我可以手动执行此操作,par(mfrow=c(rows, cols))然后分别plot(...)为每个系列执行此操作,但由于要绘制大量系列,这是不可行的.或者我可以写一个for循环来处理它,但必须有更好的方法来实现它.

如果不按面板逐个手动执行此操作,我该怎么办?如果有更好的方法可以在一个图中可视化所有系列的聚合视图,欢迎提出建议.例如,如果有一种方法可以在没有单独面板的情况下执行此操作.

后续问题

关于ggplot2在Ben的答案中格式化解决方案:

1)目前,列标题(不知道确切名称,但"系列标题")位于右侧,呈90°角,因此它们相互重叠,因为名称是国家名称.我希望那些位于每个面板左侧的角度为0°.

2)此外,目前每个面板都有自己的y轴刻度标签0和1,在每个面板的LH侧,这些都没有必要,所以我想将它们删除.

Ben*_*ker 5

最简单的方法是将数据重新整形为长形(例如reshape2::melt()如下),然后使用latticeggplot2.

dd <- read.table(header=TRUE,text="
year   A   B   C   D
1990   0   0   1   0
1991   0   1   1   0
1992   0   0   0   1
1993   1   1   0   0")

## make category names longer
names(dd) <- c("year","Aardvark","Behemoth","Cataclysm","Disaster")
library("reshape2")
ddm <- melt(dd,id.var="year")
Run Code Online (Sandbox Code Playgroud)

格子

library("lattice")
## you could use type="h" here, but I like "b" better ...
xyplot(value~year|variable,data=ddm,type="b",
       layout=c(1,4), ## stack (1 column, 4 rows); can also
                      ## use a third element of layout to split
                      ## into multiple pages
       as.table=TRUE  ## stack top-to-bottom
      ) 
Run Code Online (Sandbox Code Playgroud)

GGPLOT2

更新:删除y轴刻度标签; 使用此答案旋转刻面标签.

library("ggplot2"); theme_set(theme_bw())
ggplot(ddm,aes(year,value))+geom_point()+geom_line()+
    facet_grid(variable~.)+  ## or use facet_wrap(~variable)
    theme(panel.margin=grid::unit(0,"lines"))+  ## squash panels together
       scale_y_continuous(breaks=c(0,1),labels=rep("",2))+
    theme(strip.text.y = element_text(angle = 0))
Run Code Online (Sandbox Code Playgroud)