2017-06-17 32 views
1

我需要用ggplot2创建图的国王,我用geom_bar,geom_histogram尝试了很多东西,没有任何成功。 有什么建议吗?按ggplot2排序的聚类图

问候

enter image description here

dataset <- data.frame(
     day=seq(from=as.Date("2010-01-01"), to=as.Date("2010-03-01"), by = 1), 
     cluster=factor(sample(x=1:3,size = 60,replace = TRUE)) 
    ) 

回答

1

您正在寻找geom_rect,并在ggplot2问题往常一样,这是一种变相的 数据操作的问题。你想使一个数据帧就可以送入geom_rect所以你需要xminxmax ...

我在这里做一些假设,根据你使用,你可能需要将其适应实际数据样本数据你有。

dataset %>% 
    mutate(step = cumsum(lag(cluster, 1, default = TRUE) != cluster)) %>% 
    group_by(step) %>% 
    summarise(cluster = first(cluster), date_min = min(day)) %>% 
    mutate(date_max = lag(date_min, 1)) %>% 
    select(-step) %>% 
    ggplot() + geom_rect(aes(xmin=date_min, xmax = date_max, ymin=0, ymax=1, fill = cluster, col = cluster)) 

的关键是step变量,每次递增更改cluster柱:

dataset %>% 
    mutate(step = cumsum(lag(cluster, 1, default = TRUE) != cluster)) %>% 
    head 
     day cluster step 
1 2010-01-01  1 0 
2 2010-01-02  3 1 
3 2010-01-03  3 1 
4 2010-01-04  2 2 
5 2010-01-05  3 3 
6 2010-01-06  2 4 

然后你group_by这个step变量。其余的是经典的dplyr,然后是ggplot2

我明白了,这正是我所理解的你想要的。其余的只是化妆品。

enter image description here

2

你也可以使用geom_tile,而不是改变你的数据集:

ggplot(dataset) + geom_tile(aes(x=day, y = 1,fill=cluster)) + expand_limits(y=c(-2,4)) + 
    theme(axis.title.y=element_blank(), 
    axis.text.y=element_blank()) 

enter image description here

要改变杆的厚度,就可以改变expand_limits()

+0

太好了。我总是忘记geom_tile :-) –

+0

@RomainFrancois,谢谢!尽管在有大量数据的情况下,我觉得你的解决方案更可取,因为不是像'geom_tile'那样绘制每天的值,而是连续组合 - 可能会使得渲染效果更好,被添加到情节。 –