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

标签 r csv plot scatter

我的数据以 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")

这产生

enter image description here

要了解其工作原理,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

产生

enter image description here

关于r - 如何为 R 中散点图中的类赋予颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30894789/

相关文章:

r - 如何更改点阵中的点大小?

r - 将多列合并为一个列表列

r - plotly 中的 add_trace,用于我的特定图形的跟踪

csv - Hive - 加载以管道开头的管道分隔数据

在 R 中重新排列多个矩阵的形状

opencv - 绘制相机轨迹

python - 如何使用两个单值用 matplotlib 绘制条形图?

r - 仅保留特定列的所有行中的字母 - 删除所有其他字符

r - java.lang.OutOfMemoryError : GC overhead limit exceeded

c++ - 如何在 C++ 的单元格中读取带有换行符和逗号字符的 CSV 文件