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

ifr*_*eak 35 r ggplot2

我有以下数据框:

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
Run Code Online (Sandbox Code Playgroud)

我需要在同一个图中绘制所有这些列(在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")
Run Code Online (Sandbox Code Playgroud)

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

Vin*_*ynd 49

最简单的方法是将数据转换为"高"格式.

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)
Run Code Online (Sandbox Code Playgroud)

  • @ifreak怎么可能有人将此代码应用于原始的完整数据框架,该数据框架仅存在于您的计算机上,而您还没有提供?并且说"它不起作用"是关于可以想象的最不有用的评论,因为它没有提供关于它如何或为什么不起作用的任何信息. (5认同)
  • 为了能够提供帮助,我们需要知道您所说的“它不起作用”是什么意思:是否有任何错误消息? (2认同)

Ale*_*son 12

非常简单的解决方案:

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")
Run Code Online (Sandbox Code Playgroud)

请注意它只是绘制数据,并没有绘制任何回归线.


shi*_*iny 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)
Run Code Online (Sandbox Code Playgroud)

数据

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)
Run Code Online (Sandbox Code Playgroud)