R/ggplot2 - 数据帧的 Y 轴值

发布于 2024-11-09 00:26:29 字数 242 浏览 1 评论 0原文

我有三个具有这种结构的数据框(但值不同):

V1 V2
2010-04-30 30
2010-07-31 17
2010-10-02 20

我想在 ggplot2 中制作一个包含 3 条线的折线图,每个数据集一条。问题是我想在 Y 轴上显示相对于每个数据集而不是全局数据集的百分比。

我该怎么做?我应该合并两个数据帧,还是为不同的数据帧调用三次 geom_line() 并更改 Y 值?

I have three dataframes with this structure (but different values):

V1 V2
2010-04-30 30
2010-07-31 17
2010-10-02 20

I want to do a line chart in ggplot2 with 3 lines, one for each dataset. The problem is that i want to display in the Y axis the percentage relative to each dataset and not the global one.

How can i do this? Should i merge the two dataframes, or call three times geom_line() for the different dataframes and change there Y value?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

等风来 2024-11-16 00:26:29

有很多方法可以做到这一点,有些可能比这更简洁,但这可以帮助您实现这一目标:

#Create three data frames along the lines of your example
df1 <- data.frame(V1=c("2010-04-30","2010-07-31","2010-10-02"),V2=c(30,17,20))
df2 <- data.frame(V1=c("2010-04-30","2010-07-31","2010-10-02"),V2=c(10,5,42))
df3 <- data.frame(V1=c("2010-04-30","2010-07-31","2010-10-02"),V2=c(3,15,12))

#Combine them and create a variable to distinguish between them
df <- rbind(df1,df2,df3)
df$type <- rep(letters[1:3],each=3)

#Use ddply to calculate the proportion by group (there are _lots_ of other ways to do this part)
df <- ddply(df,.(type),.fun=function(x){x$V3 <- x$V2/sum(x$V2);return(x)})
#And plot
ggplot(df,aes(x=as.Date(V1),y=V3)) + geom_line(aes(group=type,colour=type))

There are lots of ways to do this, some probably pithier than this, but this gets you there:

#Create three data frames along the lines of your example
df1 <- data.frame(V1=c("2010-04-30","2010-07-31","2010-10-02"),V2=c(30,17,20))
df2 <- data.frame(V1=c("2010-04-30","2010-07-31","2010-10-02"),V2=c(10,5,42))
df3 <- data.frame(V1=c("2010-04-30","2010-07-31","2010-10-02"),V2=c(3,15,12))

#Combine them and create a variable to distinguish between them
df <- rbind(df1,df2,df3)
df$type <- rep(letters[1:3],each=3)

#Use ddply to calculate the proportion by group (there are _lots_ of other ways to do this part)
df <- ddply(df,.(type),.fun=function(x){x$V3 <- x$V2/sum(x$V2);return(x)})
#And plot
ggplot(df,aes(x=as.Date(V1),y=V3)) + geom_line(aes(group=type,colour=type))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文