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' is an unrecognized escape in character string starting "C:\R"

r - 在ggplot中绘制径向背景

r - 在 ggplot/ggmap 中省略一些边框

r - ggplot 将平均线添加到特定月份的方面

r - 如何自定义或显示模式栏?

c++ - 使用 R 数学独立库的 C++ 中的矩阵/vector ?

r - 汇集估算数据集的 glmers

r - Shiny 打开多个浏览器标签

r - position_dodgev 导致 geom_line 中连接点的顺序错误

r - R中的lpsolve包