如何将geom_line添加到R中的堆叠barplot

时间:2018-11-21 11:37:33

标签: r ggplot2 bar-chart

下面是我的代码。我试图在堆积的条形图的顶部添加一行(来自不同csv文件的数据),但是它行不通,错误提示“找不到对象变量”。在不添加geom_line的情况下,堆叠的barplot起作用,因此我认为是造成问题的那条线。关于如何解决此问题的任何想法?

a <- read.csv("data.csv", header=TRUE, sep=",")

line1 <- read.csv("data1.csv", header=TRUE, sep=",")

line2 <- data.frame(line1)

library(reshape2)
c <- melt(a, id.var="day")

library(ggplot2)
a <- ggplot(c, aes(x=day, y=value, fill=variable)) +

 geom_bar(stat="identity", aes(x=day, y=value), width=0.7) +

 geom_line(data=line2, aes(x=day, y=value), color="black", stat="identity") 
 +

 scale_fill_manual(values = c("black", "grey47", "grey")) +

 scale_x_continuous(breaks = round(seq(min(m$day), max(m$day), by = 1),0))

 print(a)

3 个答案:

答案 0 :(得分:0)

根据您对数据结构的评论,我认为这可能有助于先连接数据框,然后使用一个数据集构建图。您可以尝试:

library(dplyr)
c <- c %>%
  left_join(line2 %>%
              rename(value_line2 = value),
            by="day")

然后调整geom_line()

geom_line(data=c, aes(x=day, y=value_line2), color="black", stat="identity")

这可能会有所帮助。请告诉我是否无法按预期加入数据。

答案 1 :(得分:0)

如果不清楚,这就是我在上面的评论中所说的:

library(ggplot2)
a <- ggplot(c, aes(x=day, y=value)) +
     geom_bar(stat="identity", aes(x=day, y=value, fill=variable), width=0.7) +
     geom_line(data=line2, aes(x=day, y=value), color="black", stat="identity")

答案 2 :(得分:0)

以下是生成下图的完整代码示例。
我已经更改了变量的名称,以使其更加一致。您已将文件"data.csv"中的data.frame和ggplot指令a的结果都命名了。

library(reshape2)
library(ggplot2)

a <- read.csv("~/data.csv")
line1 <- read.csv("~/data2.csv")

long <- melt(a, id.var = "day")

g <- ggplot(long, aes(x = day, y = value)) +
  geom_bar(aes(x = day, y = value, fill = variable), 
           stat = "identity", width = 0.7) +
  geom_line(data = line1, 
            aes(x = day, y = value), 
            color = "black") +
  scale_fill_manual(values = c("black", "grey47", "grey")) +
  scale_x_continuous(breaks = min(long$day):max(long$day))

print(g)

enter image description here

dput格式的数据。

a <-
structure(list(day = 1:31, emigration = c(6L, 6L, 6L, 6L, 5L, 
3L, 1L, 9L, 8L, 7L, 6L, 4L, 3L, 1L, 2L, 4L, 5L, 6L, 8L, 7L, 5L, 
4L, 1L, 2L, 4L, 9L, 8L, 7L, 6L, 4L, 3L), security = c(5L, 5L, 
5L, 5L, 6L, 6L, 8L, 9L, 9L, 9L, 8L, 8L, 5L, 7L, 7L, 6L, 5L, 5L, 
4L, 3L, 2L, 2L, 2L, 2L, 4L, 9L, 7L, 6L, 4L, 3L, 2L), checkin = c(4, 
6, 9, 1, 3, 5, 7, 9, 8, 6, 4, 2, 1, 3, 4, 5, 6, 7, 8, 8, 2, 1, 
2, 3, 4, 5, 7, 8, 9, 1, 1)), class = "data.frame", 
row.names = c(NA, -31L))

line1 <-
structure(list(day = 1:31, value = c(12, 11, 10, 8, 7, 6, 6, 
6, 7, 8, 14, 6, 6, 6, 8, 8, 10, 10, 12, 12, 12, 13, 13, 14, 15, 
15, 10, 10, 10, 10, 12)), class = "data.frame", 
row.names = c(NA, -31L))