2017-09-03 39 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