hannes101 - 1 month ago 5
R Question

# Combine a barchart and line chart with ggplot2

I know that adding a second axis to a ggplot2 plot is actually not welcome, but in my case it does make sense, at least for me.
I try to show the development of an aggregate variable for a certain industry, let's say turnover, and I would like to also show the number of companies, which were part of that industry at each point in time. So that you could see that the increase in aggregate turnover is not fully driven by the number of companies, but rather by the increase in turnover at the companies. I could calculate the average of course, but then again I could not really show, what is actually driving the increase/decrease.

`````` dt.company.data <- data.table(year = 2000:2015, Num.Companies = c(385, 374,
365, 390, 410, 425, 429, 427, 410, 407, 434, 444, 519, 506, 463,
388), Value = c(3155.69125, 4086.579, 7553.78425, 7515.07275,
7571.95025, 6884.45075, 20009.79475, 15886.1025, 9813.0265, 11232.50775,
11323.67375, 19137.25225, 21569.86375, 20616.758, 20030.20875,
27840.66625))
``````

Obviously the following code does not work, since the scales are so different for both variables.

``````ggplot(dt.company.data) +
geom_bar(aes(x = year , weight = Num.Companies)) +
geom_line(aes(x = year, y = Value))
``````

by scaling the `Value` to the range of `num.companies` you can achieve this. I added a dummy `id` to generate the legend.

``````dt.company.data\$id <- factor(1)

ggplot(dt.company.data) +
geom_bar(aes(x = year , weight = Num.Companies), fill = "grey70") +
geom_line(aes(x = year, y = Value/100, colour = id)) +
scale_colour_manual(name = "Legend", labels = c("Value in 100"), values = c("black"))
``````

the outcome looks like this: