简体   繁体   中英

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!

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))

在此处输入图片说明

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)

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM