绘制两列为条形图,第三列为线形图ggplot

时间:2020-02-05 15:26:12

标签: r ggplot2 tidyr

我的df看起来像这样:

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

我想将alo和bor列绘制为同一图上的两个条形图,因此我收集了df。但是,我希望将汽车列作为折线图而不是同一图上的条形图。

当前,我的绘图代码为:

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

请提供有关如何为第三列而不是条形图添加折线图的建议。谢谢!

1 个答案:

答案 0 :(得分:6)

gather条形图中所需的列:

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

如果您想在图例中使用car标签,请尝试一些技巧:

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