ggplot:绘制两条线和一条线?

时间:2019-11-25 03:52:16

标签: r ggplot2

我需要绘制两条线和一条线。我有3个数据帧,如下:

require(ggplot2)    
df.0 <- data.frame(x = c(1:5), y = rnorm(5))
df.1 <- data.frame(x = c(1:5), y = rnorm(5))
df.2 <- data.frame(x = c(1:5), y = runif(5))

ggplot(df.0, aes(x=x, y=y)) + 
  geom_line(aes(x=x, y=y))+
  geom_bar(data=df.1, aes(x=x, y=y),stat = "identity",position="dodge")+
  geom_bar(data=df.2, aes(x=x, y=y),stat = "identity",position="dodge")

我无法以正确的方式绘制线条和线条。它应该如下图所示。

Plot i need to make

我对ggplot2不熟悉。我已经阅读了很多链接,但找不到与我的问题类似的帖子。 感谢您的时间和关注。

1 个答案:

答案 0 :(得分:1)

组合数据框-至少两个条形图。躲避是在单个geom_bar图层中完成的,而不是在两个单独的图层之间进行的。

df_bar = rbind(df.1, df.2)
df_bar$id = rep(c("df.1", "df.2"), times = c(nrow(df.1), nrow(df.2)))

ggplot(df.0, aes(x = x, y = y)) + 
  geom_line() +
  geom_col(data = df_bar, aes(fill = id), position="dodge")

enter image description here

其他更改:无需在每一层重复aes(x = x, y = y)。如果它在原始ggplot()中,它将被继承。另外,geom_colgeom_bar(stat = 'identity')的一种好方法。

相关问题