4

Is it possible to change the position of lines, such that they start and end at the edges of stacked bar charts instead of in the center?

R code:

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

Current image:

enter link description here

Data:

http://pastebin.com/D7uSKBmA

Sandy Muspratt
  • 31,719
  • 12
  • 116
  • 122

1 Answers1

1

It seems that what is required is segments rather than lines; that is, use geom_segment() in place of geom_line(). geom_segment requires x and y coordinates for the start and end points of the segments. Getting the end y value is a bit unwieldy. But it works with your data frame assuming that there are 30 observations for each "Well", and that the order for "Sequence" is the same for each "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

Sandy Muspratt
  • 31,719
  • 12
  • 116
  • 122
  • Thanks for your answer. The amount of observations for each well is not the same, but it still seems like it works. When I try to do this I get the bars but no lines. And I get a bunch of warning messages, one of them is: 'In eval(expr, envir, enclos) : NAs introduced by coercion', but most of them are: 'In loop_apply(n, do.ply) : Removed 3 rows containing missing values (geom_segment).' I am obviously a bit of a newbie to R, but it seems to run smoothly with the exception of the missing segments. Any suggestions for improvement? – Asta-Selloane Sekamane May 20 '15 at 12:50
  • Apologies for the delay. I'm not sure why you are getting these warnings and errors. I don't. With regard to the data you provided, for `DepSequence == "Original"`, I get 30 observations per "Well", and the order for "Sequence" remains the same within each "Well". I tried selecting a few other "DepSequences" - the same applies. In each case, the `geom_segment` chart and the `geom_line` chart produced the same lines; the only difference is that in the `geom_segment` chart, the lines begin and end at the edge of the stacked bars. – Sandy Muspratt May 22 '15 at 00:37