r - 使用 ggplot 同时重叠折线图和条形图

标签 r ggplot2

想用 ggplot 将折线图重叠在条形图上。 假设V1、V2是条形图的数据,V3应以线的形式呈现。 如何同时完成子集和不同的geom?

library(data.table)
library(ggplot2)
set.seed(100)
dat <- data.frame(Axis=letters[1:10],V1=1:10, V2=runif(10, 1,10), V3=10:1)
dat <-melt(data,id.var="Axis",measure.var=c("V1","V2","V3"))

会是这样吗?

ggplot(dat, aes(x=Axis)) + 
geom_bar(stat="identity", aes(, y= value[------]))+   # V1, V2 for bars
geom_line(aes(y=value[-----))                         # V3 for line

我尝试制作 V1、V2 的子集,并制作条形图,但无法将 V3 作为一条线插入图表上。

非常感谢

感谢@dash2,我稍微改变了他的代码,并使其看起来更清晰。

ggplot(dat, aes(x = Axis)) + 
  geom_col(aes(y = V1), fill = "darkred", alpha = .5, width=0.4) + 
  geom_col(aes(y = V2), fill = "blue", alpha = .5, 
           position = position_nudge(x = 0.4),width=0.4) + 
  geom_line(aes(y = V3, group = NA))

enter image description here

最佳答案

最简单,不熔化。

ggplot(data, aes(x = Axis)) + 
  geom_col(aes(y = V1), fill = "darkred", alpha = .5) + 
  geom_col(aes(y = V2), fill = "blue", alpha = .5, 
        position = position_nudge(x = 0.2)) + 
  geom_line(aes(y = V3, group = NA))

enter image description here

为品味增添美感。

group 参数是必要的。我认为离散刻度(如此处的 x 轴)会自动对它们的值进行分组,让您得到 1 组并且没有绘制任何线......一致,但不直观。

关于r - 使用 ggplot 同时重叠折线图和条形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49590265/

相关文章:

r - 在R中串联重复的数据框值

r - R reshape2 中 cast() 调用的自定义聚合函数出错

R 函数对列表对象中保存的 data.frames 进行排序

r - R 中的桑基图

r - 在 R 中的序列中优雅地为 ggplot2 轴标签创建字符串

r - 如何将我的散点图转换为正确的散点图?

r - 如何在ggplot2中使用斜体作为构面标签?

r - 如何在 packageVersion 之后以字符串形式获取完整版本?

r - 如何更改 ggplot2 中复杂填充的颜色?

r - ggplot几何点,修改文本