R中装配的水平线图

时间:2012-02-24 14:37:35

标签: r graph line ggplot2 lattice

我有大量数据如下,但这只是一点点样本。

pos <- c(1, 3, 5, 8, 10, 12)
start <- c(1,3, 6, 7, 10, 11)
end <- c(5, 6, 9, 9, 13, 12)

Qunatative变量Pos将是Y轴,X轴将是anthor X变量(定量)。每个Pos值的水平条长度由起点和终点定义。例如,1的行将从1开始,并在x轴的3处结束。

以下是所需图形输出的粗略草图。

enter image description here

2 个答案:

答案 0 :(得分:5)

在基地R ......

plot(pos, type = 'n', xlim = range(c(start, end)), ylim = c(13,0))
grid()
segments(start, pos, end, pos)

让它更像你的身材......

r <- par('usr') 
plot(pos, type = 'n', xlim = range(c(start, end)), ylim = c(13.5,0.5), xlab = '', 
    xaxt = 'n', yaxt = 'n', panel.first = rect(r[1], r[3], r[2], r[4], col = 'goldenrod'))
# abline(h = 1:13, col = 'white')
# abline(v = 1:13, col = 'white')
grid(lty = 1, col = 'white')
axis(1, 1:13, 1:13, cex.axis = 0.8)
axis(2, 1:13, 1:13, las = 1, cex.axis = 0.8)
segments(start, pos + 0.5, end, pos + 0.5, lwd = 2)

答案 1 :(得分:3)

将包ggplot2geom_segment一起使用以绘制线条。

首先将您的数据合并到data.frame,因为这是ggplot所需的数据结构:

dat <- data.frame(
  pos = c(1, 3, 5, 8, 10, 12),
  start = c(1,3, 6, 7, 10, 11),
  end = c(5, 6, 9, 9, 13, 12)
)

创建情节:

library(ggplot2)
ggplot(dat) + 
    geom_segment(aes(x=start, y=pos, xend=end, yend=pos), color="blue", size=3) +
    scale_y_reverse()

enter image description here