绘制 geom_line() 和 geom_point() - 不同长度的数据 [英] Plotting geom_line() and geom_point() - data of different lengths
问题描述
我试图在 ggplot 中绘制时间序列,以便每年的值与 geom_line() 相关联,并且总数在 x 轴的最右侧显示为单独的 geom_point().
I am trying to plot a timeseries in ggplot such that the yearly values are connected with geom_line() and the totals appear as separate geom_point() at the far right of the x-axis.
我试图在美学中对数据进行子集化,但出现错误:
I have tried to subset the data within the aesthetic, but get the error:
Aesthetics must be either length 1 or the same as the data (1): x, y
我也尝试使用两个不同的数据框,但得到了类似的错误.对不起,如果这是一个基本问题,但我没有找到解决方案的运气.
I have also tried to use two different data frames but get a similar error. Sorry if this is a basic question, but I have had no luck finding a solution.
请参阅下面的虚拟数据集和 ggplot2 脚本.我希望最终的情节看起来像这样,但没有连接2017"和总计"的线,最好不必求助于在 Adobe Illustrator 中编辑输出!
Please see the dummy dataset and ggplot2 script below. I would like the final plot to look like this but without the line connecting '2017' and 'total', and preferably without having to resort to editing the output in Adobe 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"))
推荐答案
Solution I went with, as provided by the good folk of #rstats over on 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'))
这篇关于绘制 geom_line() 和 geom_point() - 不同长度的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!