gpt4 book ai didi

r - 将两列绘制为条形图,将第三列绘制为折线图 ggplot

转载 作者:行者123 更新时间:2023-12-01 10:17:22 26 4
gpt4 key购买 nike

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

请告知如何为第三列添加折线图而不是条形图。谢谢!

最佳答案

收集您想要在条形图中显示的列:

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

关于r - 将两列绘制为条形图,将第三列绘制为折线图 ggplot,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60079051/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com