在R中将多个列绘制在同一图表上

54

我有以下数据框:

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")

但它只绘制了第一个(X轴和A)

4个回答

73

最简单的方法是将您的数据转换为“长”格式。

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)

顺便说一句,这个不起作用:/ - ifreak
11
“@ifreak怎么能够将这段代码应用到原始完整的数据框上呢?毕竟它只存在于你的电脑上,而你没有提供它。说“它不工作”是最没有帮助的评论之一,因为它并没有提供任何关于代码为何不能运行或如何不能运行的信息。” - joran
我的数据框大约有500行。但我尝试复制Vincent提供的相同代码并在我的脚本之外尝试,但它也没有起作用。这就是我所说的它没有起作用的意思。 - ifreak
2
为了能够帮助您,我们需要知道“它没有工作”是什么意思:是否有任何错误消息? - Vincent Zoonekynd
这个解决方案没有在同一张图上绘制变量。 - ABCD
显示剩余11条评论

14
一个非常简单的解决方案:
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
使用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
感谢 tidyverse 选项。运行得很好。 - TheSciGuy

0
为了选择要绘制的列,我在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()

请谷歌搜索“整洁数据”以了解更多关于长格式/宽格式的信息。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接