2017-09-03 79 views
2

我的工作的数据是一个簇的数据,其中一个组内的多个观察,我产生的毛虫情节和要标记的每个组(zipid),不是每一个线路,我的电流图和代码如下所示:ř图表:标签由组

text = hosp_new[,c("zipid")] 
    ggplot(hosp_new, aes(x = id, y = oe, colour = zipid, shape = group)) + 
    # theme(panel.grid.major = element_blank()) + 
    geom_point(size=1) + 
    scale_shape_manual(values = c(1, 2, 4)) + 
    geom_errorbar(aes(ymin = low_ci, ymax = high_ci)) + 
    geom_smooth(method = lm, se = FALSE) + 
    scale_linetype_manual(values = linetype) + 
    geom_segment(aes(x = start_id, xend = end_id, y = region_oe, yend = region_oe, linetype = "4", size = 1.2)) + 
    geom_ribbon(aes(ymin = region_low_ci, ymax = region_high_ci), alpha=0.2, linetype = "blank") + 
    geom_hline(aes(yintercept = 1, alpha = 0.2, colour = "red", size = 1), show.legend = "FALSE") + 
    scale_size_identity() + 
    scale_x_continuous(name = "hospital id", breaks = seq(0,210, by = 10)) + 
    scale_y_continuous(name = "O:E ratio", breaks = seq(0,7, by = 1)) + 
    geom_text(aes(label = text), position = position_stack(vjust = 10.0), size = 2) 

卡特彼勒情节:

caterpillar plot

每种颜色代表一个区域,我只想一个标签/每个地区,但不知道如何删除重复标签在这张图中。 有什么想法?

+2

欢迎堆栈溢出!请记住,在'r'标记中,您必须在您的示例中提供完全可重现的可运行代码/数据,包括库语句,示例数据等。请相应地编辑您的问题。 –

+0

您可以创建与标签和各医院ID的中点第二数据帧,并传递到geom_text,或者你可以使用方面,还是......但对于更具体的帮助,一个小例子,数据集应加 - 即一个例如hosp_new的只有少数医院的id:如添加的'dput结果(droplevels(hosp_new [hosp_new的$ id%%的样品(hosp_new $ ID中,3)))'你的问题。 – user20650

回答

5

的关键是为每个zipidgeom_text返回只有一个值,而不是多个值。如果我们希望每个zipid标签位于其群的中间,那么我们可以使用的id平均值为x坐标为每个标签。标签的在下面的代码中,我们使用stat_summaryh(从ggstance包)来计算该平均id值x坐标和返回单个标签为每个zipid

library(ggplot2) 
theme_set(theme_bw()) 
library(ggstance) 

# Fake data 
set.seed(300) 
dat = data.frame(id=1:100, y=cumsum(rnorm(100)), 
       zipid=rep(LETTERS[1:10], c(10, 5, 20, 8, 7, 12, 7, 10, 13,8))) 

ggplot(dat, aes(id, y, colour=zipid)) + 
    geom_segment(aes(xend=id, yend=0)) + 
    stat_summaryh(fun.x=mean, aes(label=zipid, y=1.02*max(y)), geom="text") + 
    guides(colour=FALSE) 

enter image description here

你也可以使用小面,由@ user20650提及。在下面的代码,panel.spacing.x=unit(0,'pt')消除小面板之间的空间,同时增加了expand=c(0,0.5) 0.5单位填充的每个面板的侧面。它们一起确保了刻度线之间的间隔,即使在各个方面也是如此。

ggplot(dat, aes(id, y, colour=zipid)) + 
    geom_segment(aes(xend=id, yend=0)) + 
    facet_grid(. ~ zipid, scales="free_x", space="free_x") + 
    guides(colour=FALSE) + 
    theme_classic() + 
    scale_x_continuous(breaks=0:nrow(dat), 
        labels=c(rbind(seq(0,100,5),'','','',''))[1:(nrow(dat)+1)], 
        expand=c(0,0.5)) + 
    theme(panel.spacing.x = unit(0,"pt")) 

enter image description here