r - How can a line be overlaid on a bar plot using ggplot2? -


i'm looking way plot bar chart containing 2 different series, hide bars 1 of series , instead have line (smooth if possible) go through top of bars hidden series have been (similar how 1 might overlay freq polynomial on histogram). i've tried example below appear running 2 problems.

first, need summarize (total) data group, , second, i'd convert 1 of series (df2) line.

df <- data.frame(grp=c("a","a","b","b","c","c"),val=c(1,1,2,2,3,3))   df2 <- data.frame(grp=c("a","a","b","b","c","c"),val=c(1,4,3,5,1,2))   ggplot(df, aes(x=grp, y=val)) +        geom_bar(stat="identity", alpha=0.75) +       geom_bar(data=df2, aes(x=grp, y=val), stat="identity", position="dodge") 

perhaps sample data aren't representative of real data working with, there no lines drawn df2. there 1 value each x , y value. here's modifed version of df2 enough data points construct lines:

df <- data.frame(grp=c("a","a","b","b","c","c"),val=c(1,2,3,1,2,3)) df2 <- data.frame(grp=c("a","a","b","b","c","c"),val=c(1,4,3,5,0,2))  p <- ggplot(df, aes(x=grp, y=val))  p <- p + geom_bar(stat="identity", alpha=0.75)   p + geom_line(data=df2, aes(x=grp, y=val), colour="blue") 

alternatively, if example data above correct, can plot information point geom_point(data = df2, aes(x = grp, y = val), colour = "red", size = 6). can change color , size liking.

edit: in response comment

i'm not entirely sure visual freq polynomial on histogram supposed like. x-values supposed connected 1 another? secondly, keep referring wanting lines code shows geom_bar() assume isn't want? if want lines, use geom_lines(). if 2 assumptions above correct, here's approach that:

 #first let's summarise df2 group  df3 <- ddply(df2, .(grp), summarise, total = sum(val)) >  df3   grp total 1       5 2   b     8 3   c     3  #second, let's plot df3 line while treating grp variable numeric  p <- ggplot(df, aes(x=grp, y=val)) p <- p + geom_bar(alpha=0.75, stat = "identity")  p + geom_line(data=df3, aes(x=as.numeric(grp), y=total), colour = "red") 

Comments

Popular posts from this blog

asp.net - repeatedly call AddImageUrl(url) to assemble pdf document -

java - Android recognize cell phone with keyboard or not? -

iphone - How would you achieve a LED Scrolling effect? -