我的 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")
请建议我如何为第三列而不是条添加折线图。谢谢!
最佳答案
仅对条形图中所需的列进行 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))
如果您想在图例中使用
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)
关于r - 将两列绘制为条形图,将第三列绘制为折线图 ggplot,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/60079051/