user553480
user553480

Reputation: 331

Add geom_line to stacked barplot in r

I have looked a similar threads but haven't seen anything specific to my situation.

I want to add a geom_line to a fill barchart in ggplot2. I have the values I want to superimpose as a vector. Is there a simple way to do this without merging all the values into the same dataframe?

my code if relevant:

ggplot(df_region, aes(fill=as.factor(Secondary1), y=Total, x=Year)) + 
  geom_bar(position="fill", stat="identity") + 
  theme(legend.position="bottom") +
  theme(legend.title=element_blank()) +
  labs(y="Percentage of jobs", x = "Year") + scale_fill_manual(values=c("#8DA0CB"   , "#E78AC3"  )) + theme(axis.title.x = element_text( size = 14),axis.title.y = element_text(size =14))

enter image description here

Upvotes: 1

Views: 447

Answers (1)

Rui Barradas
Rui Barradas

Reputation: 76460

To plot the line, geom_line must have the y coordinates computed beforehand. This can be done with aggregate, which returns a data.frame. I have written the function to be applied as an object, but it is possible to write it as an anonymous function.

f <- function(x) x[2]/sum(x)
df_line <- aggregate(Total ~ Year, df_region, f)

Then, in geom_line set inherit.aes = FALSE.

ggplot(data=df_region, aes(x=Year, y=Total, fill=as.factor(Secondary1))) + 
  geom_bar(position="fill", stat="identity") +
  geom_line(data = df_line, mapping = aes(x = Year, y = Total), color = "red", inherit.aes = FALSE) + 
  theme(legend.position="bottom") +
  theme(legend.title=element_blank()) +
  labs(y="Percentage of jobs", x = "Year") + 
  scale_fill_manual(values=c("#8DA0CB", "#E78AC3")) + 
  theme(axis.title.x = element_text(size = 14),
        axis.title.y = element_text(size = 14))

enter image description here

Test data

set.seed(2020)
df_region <- data.frame(Year = rep(2011:2019, each = 2),
                        Secondary1 = rep(c("a", "b"), length(2011:2019)),
                        Total = sample(10, 18, TRUE))

Upvotes: 3

Related Questions