散点图的公式表示法产生意外结果

时间:2018-03-29 22:27:54

标签: r dataframe plot colors

我在地图上工作,每个点的颜色与一个响应变量成比例,并且点的大小与另一个成比例。我注意到,当我尝试使用公式表示法绘制点时,事情会变得混乱,而默认表示法会按预期执行。我以前曾多次使用公式表示法绘制地图,并认为这些符号几乎可以互换。为什么会产生不同的结果呢?我已经阅读了plot.formulaplot.default文档,但我们无法弄明白。根据{{​​3}},我想知道是否与dat强制要素的列有关,但我不确定为什么会发生这种情况。有什么想法吗?

考虑以下示例数据框dat

latitude <- c(runif(10, min = 45, max = 48))
latitude[9] <- NA
longitude <- c(runif(10, min = -124.5, max = -122.5))
longitude[9] <- NA
color <- c("#00FFCCCC", "#99FF00CC", "#FF0000CC", "#3300FFCC", "#00FFCCCC",
           "#00FFCCCC", "#3300FFCC", "#00FFCCCC",          NA, "#3300FFCC")
size <- c(4.916667, 5.750000, 7.000000, 2.000000, 5.750000, 
          4.500000, 2.000000, 4.500000,       NA, 2.000000)
dat <- as.data.frame(cbind(longitude, latitude, color, size))

根据公式表示法绘制

plot(latitude ~ longitude, data = dat, type = "p", pch = 21, col = 1, bg = color, cex = size)

产生 this并出现以下错误:graphical parameter "type" is obsolete

根据默认表示法绘图

plot(longitude, latitude, type = "p", pch = 21, col = 1, bg = color, cex = size)

工作this mess,但有相同的错误。

1 个答案:

答案 0 :(得分:1)

这有几个问题。首先,您使用cbind会将其变为matrix,尽管是暂时的,这会将您的数字转换为character。参见:

dat <- as.data.frame(cbind(longitude, latitude, color, size))
str(dat)
# 'data.frame': 10 obs. of  4 variables:
#  $ longitude: Factor w/ 9 levels "-122.855375511572",..: 6 8 9 1 4 3 2 7 NA 5
#  $ latitude : Factor w/ 9 levels "45.5418886151165",..: 6 2 4 1 3 7 5 9 NA 8
#  $ color    : Factor w/ 4 levels "#00FFCCCC","#3300FFCC",..: 1 3 4 2 1 1 2 1 NA 2
#  $ size     : Factor w/ 5 levels "2","4.5","4.916667",..: 3 4 5 1 4 2 1 2 NA 1

如果您只是 使用data.frame,那么您将获得:

dat <- data.frame(longitude, latitude, color, size)
str(dat)
# 'data.frame': 10 obs. of  4 variables:
#  $ longitude: num  -124 -124 -124 -123 -124 ...
#  $ latitude : num  47.3 45.9 46.3 45.5 46 ...
#  $ color    : Factor w/ 4 levels "#00FFCCCC","#3300FFCC",..: 1 3 4 2 1 1 2 1 NA 2
#  $ size     : num  4.92 5.75 7 2 5.75 ...
plot(latitude ~ longitude, data = dat, pch = 21, col = 1, bg = color, cex = size)

enter image description here

但现在颜色都被愚弄了。好的,问题可能是因为你的$color是一个因素,它在内部被解释为整数。试试stringsAsFactors=F

dat <- data.frame(longitude, latitude, color, size, stringsAsFactors=FALSE)
str(dat)
# 'data.frame': 10 obs. of  4 variables:
#  $ longitude: num  -124 -124 -124 -123 -124 ...
#  $ latitude : num  47.3 45.9 46.3 45.5 46 ...
#  $ color    : chr  "#00FFCCCC" "#99FF00CC" "#FF0000CC" "#3300FFCC" ...
#  $ size     : num  4.92 5.75 7 2 5.75 ...
plot(latitude ~ longitude, data = dat, pch = 21, col = 1, bg = color, cex = size)

enter image description here