首页 > 解决方案 > 使用 ggplot2 根据值的间隔生成条形图

问题描述

我有以下 R 数据表:

library(data.table)

dt1 = data.table(start = c(0, 3, 5, 7), end  = c(3, 5, 7, 10), size = c(0, 3, 2, 1))

print(dt1)
   start end size
1:     0   3    0
2:     3   5    3
3:     5   7    2
4:     7  10    1

我想用 ggplot2 绘制一个条形图,其中每个间隔都由size. 有没有明确的方法来实现这一点ggplot2

foo = data.table(x = c(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10), 
          size = c(0, 0, 0, 3, 3, 3, 2, 2, 1, 1, 1))

ggplot(data=foo, aes(x=x, y=size)) + geom_bar(stat="identity")

在此处输入图像描述

这大致是我的想法,但不正确。从 3 到 5 的间隔应该是一条实线,而不是三条线。

这是 ggplot2 的标准程序吗?

标签: rggplot2data.table

解决方案


你可以使用geom_rect()如下

ggplot(dt1,aes(xmin = start,xmax = end, ymin = 0,ymax = size)) + 
  geom_rect()

在此处输入图像描述


推荐阅读