Moshee
Moshee

Reputation: 554

plot two columns as a bar graph and third column as line graph ggplot

My df looks like this:

df <- data.frame(date = c('2016-01-01', '2017-01-01', '2018-01-01', '2019-01-01'),
                 "alo" = c(10, 11, 12.5, 9),
                 "bor" = c(18, 20, 23, 19),
                 "car" = c(100, 125, 110, 102)) %>%
  gather(-date, key = "key", value = "value")

I want to plot alo and bor columns as two bar graphs on the same plot so I gather the df. However, I want the car column as a line graph instead of a bar plot on the same graph.

Currently, my plotting code is:

ggplot(df, aes(date, value, fill = key)) +
           geom_bar(stat = 'identity', position = "dodge")

Please advice on how I can add line graph for third column instead of bar. Thank you!

Upvotes: 3

Views: 925

Answers (1)

Axeman
Axeman

Reputation: 35382

Only gather the columns you want in your bargraph:

df <- data.frame(date = c('2016-01-01', '2017-01-01', '2018-01-01', '2019-01-01'),
                 "alo" = c(10, 11, 12.5, 9),
                 "bor" = c(18, 20, 23, 19),
                 "car" = c(100, 125, 110, 102)) %>%
  gather(alo, bor, key = "key", value = "value")

ggplot(df, aes(date)) +
  geom_col(aes(y = value, fill = key), position = "dodge") +
  geom_line(aes(y = car, group = 1))

enter image description here

If you want a car label in your legend, do some trickery:

ggplot(df, aes(date)) +
  geom_col(aes(y = value, fill = key), position = "dodge") +
  geom_line(aes(y = car, group = 1, col = 'car')) +
  scale_color_manual(values = 'black') +
  labs(color = NULL, fill = NULL)

enter image description here

Upvotes: 6

Related Questions