-2

下面是我的代码。我试图在堆叠的条形图顶部添加一行(来自不同 csv 文件的数据),但是它不起作用,错误显示“找不到对象变量”。没有添加 geom_line 堆叠的条形图可以工作,所以我认为它是造成问题的线。关于我如何解决这个问题的任何想法?

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)
4

3 回答 3

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

这可能会有所帮助。如果加入数据没有按预期工作,请告诉我。

于 2018-11-21T12:12:15.860 回答
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")
于 2018-11-21T12:20:42.367 回答
0

以下是生成下图的完整代码示例。
我已经更改了您的变量名称,以使它们更加一致。你已经命名了 file 中的 data.frame"data.csv"和你的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)

在此处输入图像描述

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))
于 2018-11-21T13:14:00.013 回答