gpt4 book ai didi

r - R 中的动画 ggplot2 堆叠折线图

转载 作者:行者123 更新时间:2023-12-04 12:38:24 33 4
gpt4 key购买 nike

我正在尝试在 ggplot2 中为堆叠折线图制作动画。

这是我想要制作动画的情节: enter image description here

下面是生成类似图的代码:

#Data
mydata <- data.frame(year=rep(1:6, times=4),
activity=as.factor(rep(c("research","coursework","clinical work","teaching"), each=6)),
time=c(40, 35, 40, 60, 85, 90,
50, 40, 10, 0, 5, 0,
5, 20, 20, 40, 10, 10,
5, 5, 30, 0, 0, 0))

mydata$activity <- ordered(mydata$activity, levels = c("research","clinical work","coursework","teaching"))

labels <- data.frame(activity=c("research","coursework","clinical work","teaching"),
xaxis=c(5, 1.8, 2.5, 2.97),
yaxis=c(25, 70, 48, 90))

#Plot
ggplot(mydata, aes(x=year, y=time, fill=activity)) +
geom_area(stat="smooth", span=.35, color="black") +
theme(legend.position = "none") +
geom_text(data=labels, aes(x=xaxis, y=yaxis, label=activity)) +
ggtitle("Time in Different Activities by Year in Program") +
ylab("Percentage of Time") +
xlab("Year in Program")

我正在寻找第一张显示所有坐标轴和文本的图像。第二次迭代,我想随着时间的推移从左到右逐渐显示“研究”堆叠线(包括颜色和边框)。第三次迭代,我想从左到右逐渐揭示“临床工作”堆叠线。四、“Coursework”叠线。最后,“教学”堆叠线。

理想情况下,输出格式应该非常平滑(没有锯齿状跳跃)并且与 PowerPoint 兼容。

最佳答案

这是一个基于 R 的解决方案。它保存可以在演示文稿中迭代的单个图形 (.png)。

或者,您可以使用 ImageMagick 创建动画(例如转换为 .gif)http://www.imagemagick.org/

#Data
mydata <- data.frame(year=rep(1:6, times=4),
activity=as.factor(rep(c("research","coursework","clinical work","teaching"), each=6)),
time=c(40, 35, 40, 60, 85, 90,
50, 40, 10, 0, 5, 0,
5, 20, 20, 40, 10, 10,
5, 5, 30, 0, 0, 0))

#order the activities and then the dataframe
mydata$activity <- ordered(mydata$activity, levels = c("research","clinical work","coursework","teaching"))
mydata <- mydata[order(mydata$activity),]

#labels
labels <- data.frame(activity=c("research","coursework","clinical work","teaching"),
xaxis=c(5, 1.8, 2.5, 2.97),
yaxis=c(25, 70, 48, 90))

#creates a function to draws a plot for each activity
draw.stacks<-function(leg){
int <- leg*6
a<-ggplot(data=mydata[1:int,], aes(x=year, y=time, fill=activity))+
geom_area(stat="smooth", span=.35, color="black") +
theme_bw()+
scale_fill_discrete(limits = c("research","clinical work","coursework","teaching"), guide="none")+
theme(panel.grid.major = element_blank(),
panel.grid.minor = element_blank()) +
coord_cartesian(xlim=c(1,6),ylim=c(0,100))+
geom_text(data=labels, aes(x=xaxis, y=yaxis, label=activity)) +
ggtitle("Time in Different Activities by Year in Program") +
ylab("Percentage of Time") +
xlab("Year in Program")
print(a)
}


# save individual png figures
for (i in 0:4) {
png(paste("activity", i, "png", sep="."))
draw.stacks(i)
dev.off()
}

关于r - R 中的动画 ggplot2 堆叠折线图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28029471/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com