Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

ggplot2

I'm looking for a way to plot a bar chart containing two different series, hide the bars for one of the series and instead have a line (smooth if possible) go through the top of where bars for the hidden series would have been (similar to how one might overlay a freq polynomial on a histogram). I've tried the example below but appear to be running into two problems.

First, I need to summarize (total) the data by group, and second, I'd like to convert one of the series (df2) to a 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")
like image 912
user338714 Avatar asked Dec 02 '10 06:12

user338714


People also ask

How do you overlay a line graph in R?

To overlay a line plot in the R language, we use the lines() function. The lines() function is a generic function that overlays a line plot by taking coordinates from a data frame and joining the corresponding points with line segments.

How do I add a line to a bar plot?

Add predefined lines or bars to a chart On the Layout tab, in the Analysis group, do one of the following: Click Lines, and then click the line type that you want. Note: Different line types are available for different chart types. Click Up/Down Bars, and then click Up/Down Bars.

How do I change the width of a bar in ggplot2?

To Increase or Decrease width of Bars of BarPlot, we simply assign one more width parameter to geom_bar() function. We can give values from 0.00 to 1.00 as per our requirements.


1 Answers

You can get group totals in many ways. One of them is

with(df, tapply(val, grp, sum))

For simplicity, you can combine bar and line data into a single dataset.

df_all <- data.frame(grp = factor(levels(df$grp)))
df_all$bar_heights <- with(df, tapply(val, grp, sum))
df_all$line_y <- with(df2, tapply(val, grp, sum))

Bar charts use a categorical x-axis. To overlay a line you will need to convert the axis to be numeric.

ggplot(df_all) +
   geom_bar(aes(x = grp, weight = bar_heights)) +
   geom_line(aes(x = as.numeric(grp), y = line_y))

enter image description here

like image 112
Richie Cotton Avatar answered Sep 22 '22 00:09

Richie Cotton