【问题标题】:Plotting geom_line() and geom_point() - data of different lengths绘制 geom_line() 和 geom_point() - 不同长度的数据
【发布时间】:2017-06-02 05:29:29
【问题描述】:

我正在尝试在 ggplot 中绘制一个时间序列,以便年度值与 geom_line() 连接,并且总数显示为 x 轴最右侧的单独 geom_point()。

我尝试在审美范围内对数据进行子集化,但出现错误:

Aesthetics must be either length 1 or the same as the data (1): x, y

我也尝试使用两个不同的数据框,但得到了类似的错误。抱歉,如果这是一个基本问题,但我没有找到解决方案。

请参阅下面的虚拟数据集和 ggplot2 脚本。我希望最终的情节看起来像这样,但没有连接“2017”和“总计”的线,最好不必求助于在 Adob​​e Illustrator 中编辑输出!

任何帮助表示赞赏。

library(ggplot2)

##synthetic data
Year <- seq(1996,2017)
var1 <- sample(0:10,length(Year), replace=TRUE)
var2 <- sample(0:10,length(Year), replace=TRUE)
var3 <- sample(0:10,length(Year), replace=TRUE)
var4 <- sample(0:10,length(Year), replace=TRUE)
total <- c("total",sample(0:10,4, replace=TRUE))


dat <- data.frame(Year, var1,var2,var3,var4)
dat <- rbind(dat,total)


plt <- ggplot(data=dat, aes(x=Year))
plt <- plt +
    geom_point(aes(y=var1, colour = "var1")) +
    geom_point(aes(y=var2, colour = "var2")) +
    geom_point(aes(y=var3, colour= "var3")) +
    geom_point(aes(y=var4, colour = "var4")) +
    geom_line(aes(y=var1, group=1, colour = "var1")) +
    geom_line(aes(y=var2, group=1, colour="var2")) +
    geom_line(aes(y=var3, group=1, colour="var3"))+
    geom_line(aes(y=var4, group=1, colour= "var4")) +
    scale_colour_manual("",
        breaks = c("var1", "var2", "var3", "var4"),
        values = c("#d7191c","#fdae61","#abd9e9","#2c7bb6")) 

【问题讨论】:

  • 不要将答案编辑到您的问题中,只需将其添加为下面的答案(有适当的信用)。
  • 感谢提醒,不知道礼仪是什么

标签: r plot ggplot2 subset


【解决方案1】:

最好将总数据保存在另一个 data.frame 中。重塑数据大大简化了 ggplot 命令。

##reshape data
dat <- data.frame(Year, var1,var2,var3,var4)
dat <- tidyr::gather(dat, key = var, value = value, -Year)

##data.frames of totals
total <- data.frame(Year = max(Year) + 1, var = paste0("var", 1:4), value = sample(0:10,4, replace=TRUE))

dat <- rbind(dat,total)


plt <- ggplot(data=dat, aes(x=Year, y = value, colour = var)) +
  geom_point() +
  geom_line() +
  geom_point(data = total) +
  scale_colour_manual("", values = c("#d7191c","#fdae61","#abd9e9","#2c7bb6")) +
  ##change xaxis to show "total"  
  scale_x_continuous(breaks = c(seq(min(dat$Year), max(dat$Year), 2), total$Year[1]), 
                     labels = c(seq(min(dat$Year), max(dat$Year), 2), "Total"))


plt

【讨论】:

  • 感谢您花时间查看我的问题。这个解决方案对我来说与“2017”和“总计”重叠,但在 Twitter 上提供了一个类似的解决方案,我已经编辑了原始帖子以显示它。
【解决方案2】:

我采用的解决方案由 #rstats 的好心人在 Twitter 上提供

library(dplyr)
mdat <- melt(dat, id.vars = 'Year') 
ggplot(data=mdat, aes(x= (Year), y = value, col = variable, group=variable))+
  geom_point()+
  geom_line(data=filter(mdat,Year != 'total'))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-22
    • 1970-01-01
    • 2020-11-14
    • 1970-01-01
    • 2011-11-20
    • 2014-08-22
    • 2015-09-09
    相关资源
    最近更新 更多