2017-07-28 138 views
1

我試圖使用ggplot如何添加標籤到ggplot片段?

dat <- data.frame(start <- c(-1.05113647, -0.63911585, -0.62791554), 
        end <- c(0.37491159, -0.13911585, -0.12791554), 
        order <- c("Sei whale", "Probeagle", "Northern fur seal"), 
        pos <- c(1, 2, 3)) 

ggplot(dat) + 
    geom_segment(aes(x=start, y=start, xend=end, yend=start), colour = "blue", size = 2) + 
    scale_y_reverse() + 
    xlab("PC1")+ 
    ylab(" ")+ 
    theme_linedraw() + 
    theme(panel.grid.minor = element_blank(), panel.grid.major = element_blank()) + 
    theme(aspect.ratio = 0.3) + 
    theme(legend.position="none") + 
    theme(axis.ticks = element_blank(), axis.text.y = element_blank()) 

我想知道如何將名字從「命令」,以各自細分市場增添標籤添加到段我創建了一個曲線圖。

回答

1

你可以從directlabels嘗試軟件包geom_dl()和擴大x軸位:

library(ggplot2) 
library(directlabels) 

ggplot(dat) + 
    geom_segment(aes(x = start, y = start, xend = end, yend = start), 
       colour = "blue", size = 2) + 
    scale_y_reverse() + 
    geom_dl(aes(end, start, label = order), 
      method = list(dl.trans(x = x + 0.2), "last.bumpup", cex = 0.60)) + 
    scale_x_continuous(expand = c(0, 0.2)) + 
    labs(x = "PC1", y = " ") + 
    theme_linedraw() + 
    theme(panel.grid.minor = element_blank(), panel.grid.major = element_blank()) + 
    theme(aspect.ratio = 0.7) + 
    theme(legend.position = "none") + 
    theme(axis.ticks = element_blank(), axis.text.y = element_blank()) 

其中給出:

enter image description here

注意:我改變aspect.ratio到0.7以使其更具可讀性。

+1

使用直接標籤 – akrun

+0

謝謝@steven,這正是我所期待的。一個問題是,添加geom_dl x軸上的刻度線已經消失。任何方式讓它回來? – Nomnoom

+0

@Nomnoom哦,那不是因爲'geom_dl()'。我犯了一個錯誤,在我之前的例子中使用'scale_x_discrete()'而不是'scale_x_continuous()'。我更新了答案。 –

0

您可以使用geom_text()

library(ggplot2) 

ggplot(dat) + 
    geom_segment(aes(start, start, xend = end, yend = start), 
       colour = "blue", 
       size=4) + 
    geom_text(aes((end + start)/2, 
        y = start, 
        label = order), 
       color = 'grey75', 
       size = 3, 
       nudge_y = .005) + 
    scale_y_reverse() + 
    xlab("PC1")+ 
    ylab(" ")+ 
    theme_linedraw() + 
    theme(panel.grid.minor = element_blank(), 
      panel.grid.major = element_blank(), 
      aspect.ratio = 0.3, 
      legend.position="none", 
      axis.ticks = element_blank(), 
      axis.text.y = element_blank()) 

結果不是特別漂亮海事組織,我增加了segmentsize,讓文本可見。

+0

謝謝@GGamba。你對「漂亮」的看法是正確的,但可以嘗試調整。你也知道如何改變y軸上的位置嗎?由於最後兩段「porbeagle」和「北方海狗」與第一段相比非常接近吸氣。 – Nomnoom

+0

段和文本的定位基於'start'值。 – GGamba