如何在 R 中格式化数据序列的散点图

How to format the scatterplots of data series in R

我一直在努力在 R 中创建一个看起来像样的散点图。我认为这并不困难。 经过一些研究,在我看来 ggplot 是一个允许大量格式化的选择。但是,我正在努力理解它是如何工作的。 我想创建两个数据系列的散点图,显示具有两种不同颜色的点,可能还有不同的形状,以及带有系列名称的图例。 这是我的尝试,基于 this:

year1 <- mpg[which(mpg$year==1999),]
year2 <- mpg[which(mpg$year==2008),]

ggplot() + 
  geom_point(data = year1, aes(x=cty,y=hwy,color="yellow"))  +
  geom_point(data = year2, aes(x=cty,y=hwy,color="green")) +
  xlab('cty') +
  ylab('hwy')

现在,这看起来差不多了,但是颜色不匹配(除非我突然变成了色盲)。这是为什么? 另外,如何添加系列名称和更改符号形状?

你想要:

library(ggplot2)    
ggplot(mpg, aes(cty, hwy, color=as.factor(year)))+geom_point()

不要构建 2 个不同的数据帧:

df <- mpg[which(mpg$year%in%c(1999,2008)),]
df$year<-as.factor(df$year)
ggplot() + 
  geom_point(data = df, aes(x=cty,y=hwy,color=year,shape=year))  +
  xlab('cty') +
  ylab('hwy')+
  scale_color_manual(values=c("green","yellow"))+
  scale_shape_manual(values=c(2,8))+
  guides(colour = guide_legend("Year"),
         shape = guide_legend("Year"))

这将适用于您当前的设置方式:

ggplot() + 
  geom_point(data = year1, aes(x=cty,y=hwy), col = "yellow", shape=1)  +
  geom_point(data = year2, aes(x=cty,y=hwy), col="green", shape=2) +
  xlab('cty') +
  ylab('hwy')