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

4

是否可以更改线的位置,使其起点和终点位于堆积条形图的边缘而不是中心位置?

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


所以它看起来像这样:http://2012books.lardbucket.org/books/using-microsoft-excel-v1.1/section_08/498259105d99351b2b2d43c2a1a1d2ca.jpg。 - Asta-Selloane Sekamane
欢迎来到SO!您所说的边缘是指顶部边缘、底部边缘还是两者都包括? - tonytonov
谢谢 :) 我的意思是@tonytonov两个都包括。 - Asta-Selloane Sekamane
1个回答

1
似乎需要的是线段而不是直线,也就是说,用geom_segment()代替geom_line()geom_segment需要线段起点和终点的x和y坐标。获取结束y值有点棘手。但是,假设每个“Well”有30个观察值,并且“Sequence”的顺序对于每个“Well”都是相同的,它可以使用您的数据框架正常工作。
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


谢谢你的回答。每个井的观测量并不相同,但看起来似乎可以工作。当我尝试这样做时,我得到了条形图,但没有线条。我收到了大量警告消息,其中一个是:“在eval(expr,envir,enclos)中:强制转换引入NAs”,但大多数都是:“在loop_apply(n,do.ply)中:删除了3行包含缺失值的数据(geom_segment)。 "显然我对R有点新手,但除了缺少的片段外,它似乎运行顺畅。有任何改进的建议吗? - Asta-Selloane Sekamane
抱歉耽搁了。我不确定为什么您会收到这些警告和错误信息,而我却没有。关于您提供的数据,对于 DepSequence == "Original",每个“井”有30个观测值,并且“序列”在每个“井”内保持不变。我尝试选择了其他几个“DepSequences” - 结果相同。在每种情况下,geom_segment 图表和 geom_line 图表生成的线条都是相同的;唯一的区别在于,在 geom_segment 图表中,线条的起点和终点位于堆叠条形图的边缘。 - Sandy Muspratt

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接