如何在堆积条形图的边缘定位线条

时间:2015-05-17 20:49:10

标签: r ggplot2

是否可以更改线条的位置,使它们在堆积条形图的边缘而不是中心处开始和结束?

R代码:

library(ggplot2)
plot11 = ggplot(CombinedThickness2[CombinedThickness2$DepSequence == "Original",], aes(x = Well, y = Thickness, fill = Sequence, alpha = Visible, width = 0.3)) + 
  geom_bar(stat = "identity") +
  scale_y_reverse() 
plot11 = plot11 + geom_line(aes(group = Sequence, y = Depth, color = Sequence))
plot11

当前图片:

enter link description here

数据:

http://pastebin.com/D7uSKBmA

1 个答案:

答案 0 :(得分:1)

似乎需要的是细分而不是细分;也就是说,使用geom_segment()代替geom_line()geom_segment需要分段的起点和终点的x和y坐标。获得结束y值有点笨拙。但它适用于您的数据框,假设每个“井”有30个观测值,并且“序列”的顺序对于每个“井”是相同的。

library(ggplot2)

df = CombinedThickness2[CombinedThickness2$DepSequence == "Original",]

# Get the y end values
index = 1:dim(df)[1]
NWell = length(unique(df$Well))
df$DepthEnd[index] = df$Depth[index + dim(df)[1]/NWell]

BarWidth = 0.3

plot11 = ggplot(df, 
   aes(x = Well, y = Thickness, fill = Sequence, alpha = Visible)) + 
   geom_bar(stat = "identity", width = BarWidth) +
   scale_y_reverse() + scale_alpha(guide = "none") 

plot11 = plot11 + 
   geom_segment(aes(x = as.numeric(Well) + 0.5*BarWidth, xend = as.numeric(Well) + (1-0.5*BarWidth), 
      y = Depth, yend = DepthEnd, color = Sequence)) 

plot11

enter image description here