提问人:ifreak 提问时间:3/2/2012 最后编辑:Henrikifreak 更新时间:1/2/2022 访问量:225438
在 R 中的同一图形上绘制多列 [重复]
Plot multiple columns on the same graph in R [duplicate]
问:
我有以下数据框:
A B C D Xax
0.451 0.333 0.034 0.173 0.22
0.491 0.270 0.033 0.207 0.34
0.389 0.249 0.084 0.271 0.54
0.425 0.819 0.077 0.281 0.34
0.457 0.429 0.053 0.386 0.53
0.436 0.524 0.049 0.249 0.12
0.423 0.270 0.093 0.279 0.61
0.463 0.315 0.019 0.204 0.23
我需要在同一图中绘制所有这些列(在 x 轴上,我想要变量 Xax,在 y 轴上绘制变量 A、B、C 和 D),并单独绘制每个变量的回归线。
我试过这个:
pl<-ggplot(data=df) + geom_point(aes(x=Xax,y=A,size=10)) +
geom_point(aes(x=Xax,y=B,size=10)) +
geom_point(aes(x=Xax,y=C,size=10)) +
geom_point(aes(x=Xax,y=D,size=10)) +
geom_smooth(method = "lm", se=FALSE, color="black")
但它只是绘制第一个(Xax 和 A)
答:
73赞
Vincent Zoonekynd
3/2/2012
#1
最简单的方法是将数据转换为“高”格式。
s <-
"A B C G Xax
0.451 0.333 0.034 0.173 0.22
0.491 0.270 0.033 0.207 0.34
0.389 0.249 0.084 0.271 0.54
0.425 0.819 0.077 0.281 0.34
0.457 0.429 0.053 0.386 0.53
0.436 0.524 0.049 0.249 0.12
0.423 0.270 0.093 0.279 0.61
0.463 0.315 0.019 0.204 0.23
"
d <- read.delim(textConnection(s), sep="")
library(ggplot2)
library(reshape2)
d <- melt(d, id.vars="Xax")
# Everything on the same plot
ggplot(d, aes(Xax,value, col=variable)) +
geom_point() +
stat_smooth()
# Separate plots
ggplot(d, aes(Xax,value)) +
geom_point() +
stat_smooth() +
facet_wrap(~variable)
评论
0赞
ifreak
3/2/2012
我没有得到解决方案??如果是 DataFrame,这是一个很小的部分,它要大得多。您能否解释答案并将其应用于原始数据帧?
0赞
ifreak
3/2/2012
顺便说一句,这是行不通的:/
11赞
joran
3/3/2012
@ifreak 任何人怎么能将此代码应用于原始的完整数据帧,该帧仅存在于您的计算机上,而您尚未提供?说“它不起作用”是可以想象到的最无用的评论,因为它没有提供任何关于它如何或为什么不起作用的信息。
0赞
ifreak
3/3/2012
我的数据框大约有 500 行。但我试图复制 Vincent 提供的相同代码并在我的脚本之外尝试过,但它也不起作用。这就是我的意思,它没有奏效。.
2赞
Vincent Zoonekynd
3/3/2012
为了能够提供帮助,我们需要知道您所说的“它不起作用”是什么意思:是否有任何错误消息?
14赞
Alessandro Jacopson
8/28/2012
#2
一个非常简单的解决方案:
df <- read.csv("df.csv",sep=",",head=T)
x <- cbind(df$Xax,df$Xax,df$Xax,df$Xax)
y <- cbind(df$A,df$B,df$C,df$D)
matplot(x,y,type="p")
请注意,它只是绘制数据,不绘制任何回归线。
5赞
shiny
9/15/2017
#3
用tidyverse
df %>% tidyr::gather("id", "value", 1:4) %>%
ggplot(., aes(Xax, value))+
geom_point()+
geom_smooth(method = "lm", se=FALSE, color="black")+
facet_wrap(~id)
数据
df<- read.table(text =c("
A B C G Xax
0.451 0.333 0.034 0.173 0.22
0.491 0.270 0.033 0.207 0.34
0.389 0.249 0.084 0.271 0.54
0.425 0.819 0.077 0.281 0.34
0.457 0.429 0.053 0.386 0.53
0.436 0.524 0.049 0.249 0.12
0.423 0.270 0.093 0.279 0.61
0.463 0.315 0.019 0.204 0.23"), header = T)
评论
1赞
TheSciGuy
7/15/2018
感谢您的选择。效果很好tidyverse
0赞
user3226167
3/2/2018
#4
为了选择要绘制的列,我在 Vincent Zoonekynd 的答案中添加了 2 行:
#convert to tall/long format(from wide format)
col_plot = c("A","B")
dlong <- melt(d[,c("Xax", col_plot)], id.vars="Xax")
#"value" and "variable" are default output column names of melt()
ggplot(dlong, aes(Xax,value, col=variable)) +
geom_point() +
geom_smooth()
谷歌“整洁数据”以了解有关高(或长)/宽格式的更多信息。
上一个:为 ggplot2 线图添加图例
下一个:在图形上添加回归线方程和 R^2
评论