繁体   English   中英

如何在R的散点图中为类赋予颜色?

[英]How to give color to a class in scatter plot in R?

我的数据以csv格式存储。 我想根据活动将数据绘制成彩色,这意味着4个不同的活动应具有4个不同的颜色。

ACTIVITY     LAT            LONG
Resting   21.14169444   70.79052778
Feeding   21.14158333   70.79313889
Resting   21.14158333   70.79313889
Walking   21.14163889   70.79266667
Walking   21.14180556   70.79222222
Sleeping  21.14180556   70.79222222

我尝试了以下代码,但是没有用:

ACTIVITY.cols <- cut(ACTIVITY, 5, labels = c("pink", "green", "yellow","red","blue"))
plot(Data$Latitude,Data$Longitude, col = as.character(ACTIVITY.cols)

plot(Data$Latitude,Data$Longitude, col=c("red","blue","green","yellow")[Data$ACTIVITY]

使用

txt <- "ACTIVITY     LAT            LONG
Resting   21.14169444   70.79052778
Feeding   21.14158333   70.79313889
Resting   21.14158333   70.79313889
Walking   21.14163889   70.79266667
Walking   21.14180556   70.79222222
Sleeping  21.14180556   70.79222222"
dat <- read.table(text = txt, header = TRUE)

一种选择是使用ACTIVITY变量作为索引来索引长度为nlevels(ACTIVITY)的颜色的向量。

cols <- c("red","green","blue","orange")
plot(LAT ~ LONG, data = dat, col = cols[dat$ACTIVITY], pch = 19)
legend("topleft", legend = levels(dat$ACTIVITY), col = cols, pch = 19, bty = "n")

这产生

在此处输入图片说明

为了了解其工作原理,将cols扩展为

> cols[dat$ACTIVITY]
[2] "green"  "red"    "green"  "orange" "orange" "blue"

因为ACTIVITY是一个因子,但在数值上存储为1,2,...,n。

还可以使用其他更高级别的解决方案,因此请考虑使用ggplot2包来简化同一图的创建。

library("ggplot2")
plt <- ggplot(dat, aes(x = LONG, y = LAT, colour = ACTIVITY)) +
  geom_point()
plt

产生

在此处输入图片说明

使用ggplot2软件包,它更快,更漂亮。

library(ggplot2)
ggplot("your dataframe") + geom_point(aes(x = Latitude, y = Longitude, colour = factor(ACTIVITY)))

使用命名向量定义颜色的方法如下:

set.seed(1);
N <- 30;
df <- data.frame(activity=sample(c('Resting','Feeding','Walking','Sleeping'),N,replace=T),lat=runif(N,0,100),long=runif(N,0,100));
cols <- c(Resting='red',Feeding='blue',Walking='green',Sleeping='yellow');
par(mar=c(5,4,4,6)+0.1,xaxs='i',yaxs='i');
plot(df$lat,df$long,xlim=c(0,100),ylim=c(0,100),col=cols[as.character(df$activity)],main='Activity Locations',xlab='Latitude',ylab='Longitude');
legend(103,80,names(cols),col=cols,pch=1,xpd=T);

情节

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM