2017-07-28 231 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