geom_segment箭头方向

时间:2017-01-26 11:43:07

标签: r ggplot2

我试图使用geom_segment绘制一些上下箭头。我将我的数据集分成2个,用于需要向上箭头和向下箭头的数据。

但是在两个地块上箭头都朝上。怎么能扭转呢?是否有一个我遗失的变量?

我使用的数据集如下所示:

GENE   START    END        STRAND
A      3000000  3000312    +
B      3001233  3090123    -

正线需要up-facing箭头,而负线需要down-facing

这是我的代码:

# split the dataset in '+' and '-'
up.arrows <- genes.data[which(genes.data$STRAND=='+'),]
up.arrows.x <- runif(length(up.arrows$START), min = 0, max = length(up.arrows))

down.arrows <- genes.data[which(genes.data$STRAND=='-'),]
down.arrows.x <- runif(length(down.arrows$START), min = 0, max = length(down.arrows))

我使用的是runif,因为我并不关心x-axis的位置。我主要担心的是y-axis

ggplot(up.arrows, aes(up.arrows.x, up.arrows$START)) +
    geom_segment(aes(xend=up.arrows.x, yend=up.arrows$STOP), 
                 arrow = arrow(length = unit(0.1, "cm")),
                 colour = 'green4') + 
    geom_text_repel(size = 3,
                    aes(label = up.arrows$GENE),
                    color = 'black') +
    theme_classic(base_size = 16)

ggplot(down.arrows, aes(down.arrows.x, down.arrows$START)) +
    geom_segment(aes(xend=down.arrows.x, yend=down.arrows$STOP), 
                 arrow = arrow(length = unit(0.1, "cm")),
                 colour = 'green4') + 
    geom_text_repel(size = 3,
                    aes(label = down.arrows$GENE),
                    color = 'black',
                    segment.color = 'black') +
    theme_classic(base_size = 16)

之后我想合并1 ggplot中的点数,因此区分updown

非常重要

1 个答案:

答案 0 :(得分:1)

解决方案是一个小问题。但我花了一些时间思考它。只需反转down-facing箭头的开始和停止即可。

而不是:

ggplot(down.arrows, aes(down.arrows.x, down.arrows$START)) +
    geom_segment(aes(xend=down.arrows.x, yend=down.arrows$STOP), 
                 arrow = arrow(length = unit(0.1, "cm")),
                 colour = 'green4') + 
    geom_text_repel(size = 3,
                    aes(label = down.arrows$GENE),
                    color = 'black',
                    segment.color = 'black') +
    theme_classic(base_size = 16)

这样做:

ggplot(down.arrows, aes(down.arrows.x, down.arrows$STOP)) +   # This is all it took
    geom_segment(aes(xend=down.arrows.x, yend=down.arrows$START), # and this
                 arrow = arrow(length = unit(0.1, "cm")),
                 colour = 'green4') + 
    geom_text_repel(size = 3,
                    aes(label = down.arrows$GENE),
                    color = 'black',
                    segment.color = 'black') +
    theme_classic(base_size = 16)