使用ggplot2向堆积柱图添加垂直偏移

时间:2017-11-05 22:14:09

标签: r ggplot2 bar-chart offset column-chart

我有几个表示钻孔轮廓的堆积柱形图。我想偏移每个钻孔的y位置来表示地面上的实际高度。

我的数据如下所示:

mShareActionProvider.setShareIntent(shareIntent);

到目前为止我的最低工作代码是:

 x layer.thickness layer.depth Petrography    BSCategory  Offset
 0             0.2         0.2        silt     Drilling1      0
 0             1.0         1.2      gravel     Drilling1      0
 0             3.0         4.2        silt     Drilling1      0
 4             0.4         0.4        silt     Drilling2     -1
 4             0.8         1.2      gravel     Drilling2     -1
 4             2.0         3.2        sand     Drilling2     -1

这是我到目前为止的输出(红色表示它应该是什么样子):

Example of drilling profiles

1 个答案:

答案 0 :(得分:2)

在这里使用geom_rect可能更容易(条形图/应该固定为零)。首先,我们需要计算每个样本的y开始和结束位置:

library(data.table)
setDT(df)[ , `:=`(start = start <- c(Offset[1] + c(0, cumsum(head(layer.thickness, -1)))),
                  end = start + layer.thickness), by = BSCategory]

geom_rect同时具有fillcolor美学,这样可以轻松为每个样本添加边框。

w <- 0.5 # adjust to desired width

ggplot(data = df, aes(xmin = x - w / 2, xmax = x + w / 2, ymin = start, ymax = end,
                      fill = Petrography, group = Petrography)) +
  geom_rect(color = "black") +
  scale_y_reverse(expand = c(0, 0), name ="Depth [m]") +
  scale_x_continuous(position = "top", breaks = df$x, labels = paste(df$BSCategory,"\n", df$x, "m"), name = "") +
  scale_fill_manual(values = c("gravel" = '#f3e03a', "sand" = '#e09637', "silt" = '#aba77d')) +
  theme_classic() +
  theme(axis.line.x = element_blank(),
        axis.ticks.x = element_blank())

enter image description here

或者,可以使用geom_segmentgeom_segment没有fill aes,因此我们需要更改为color

ggplot(data = df, aes(x = x, xend = x, y = start, yend = end, color = Petrography, group = ix)) +
  geom_segment(size = 5) +
  scale_y_reverse(expand = c(0, 0), name ="Depth [m]") +
  scale_x_continuous(position = "top", breaks = df$x, labels = paste(df$BSCategory,"\n", df$x, "m"), name = "") +
  scale_color_manual(values = c("gravel" = '#f3e03a', "sand" = '#e09637', "silt" = '#aba77d')) +
  theme_classic() +
  theme(axis.line.x = element_blank(),
        axis.ticks.x = element_blank())

enter image description here

要添加边框,请参阅Add border to segments in geom_segment