ggplot2:创建带有填充区域和填充点的地图的问题(形状21)

时间:2015-08-07 12:10:02

标签: r plot ggplot2

当我使用形状16作为点时,我可以创建具有填充区域和彩色点的地图,但是当我使用形状21并尝试根据它们所属的类别填充点时出现问题。

可重复的示例(部分取自ggplot文档):

ids <- factor(c("1.1", "2.1", "1.2", "2.2", "1.3", "2.3"))

values <- data.frame(
id = ids,
value = c(3, 3.1, 3.1, 3.2, 3.15, 3.5)
)

positions <- data.frame(
  id = rep(ids, each = 4),
  x = c(2, 1, 1.1, 2.2, 1, 0, 0.3, 1.1, 2.2, 1.1, 1.2, 2.5, 1.1, 0.3,
        0.5, 1.2, 2.5, 1.2, 1.3, 2.7, 1.2, 0.5, 0.6, 1.3),
  y = c(-0.5, 0, 1, 0.5, 0, 0.5, 1.5, 1, 0.5, 1, 2.1, 1.7, 1, 1.5,
        2.2, 2.1, 1.7, 2.1, 3.2, 2.8, 2.1, 2.2, 3.3, 3.2)
)

points <- data.frame(
  xpos = c(0.7, 1.5),
  ypos = c(1, 2.5),
  category = c("A", "B")
)

这有效:

ggplot() + 
      geom_map(data = values, aes(map_id = id, fill = value), colour =  "darkgrey",
            map = positions) + 
  expand_limits(positions) +
  coord_equal() +
  geom_point(data=points, aes(x=xpos, y=xpos, colour = category),
         size=5, shape=16)

当我尝试将类别映射到填充点(形状21)时,它失败了 &#34;错误:提供给连续刻度的离散值&#34;:

ggplot() +
  geom_map(data = values, aes(map_id = id, fill = value), map =     positions) +
  expand_limits(positions) +
  coord_equal() +
  geom_point(data = points, aes(x=xpos, y=ypos, fill = category), 
         shape = 21, colour = "black", size=5)

但是如果我将类别变量映射到颜色而不是填充:

,它就可以工作
  ggplot() +
      geom_map(data = values, aes(map_id = id, fill = value), map = positions) +
      expand_limits(positions) +
      coord_equal() +
      geom_point(data = points, aes(x=xpos, y=ypos, colour = category), 
         shape = 21, fill = "black", size=5)

我做错了什么?

1 个答案:

答案 0 :(得分:3)

lukeA如果你能够或想要依靠自动缩放,答案是好的。如果您不想依赖于颜色的自动缩放,您还可以将颜色矢量传递到映射到点的fill之外的aes

ggplot() +
  geom_map(data = values, aes(map_id = id, fill = value), map =     positions) +
  expand_limits(positions) +
  coord_equal() +
  geom_point(data = points, aes(x=xpos, y=ypos), fill=I(c("red", "green")), 
         shape = 21, colour = "black", size=5)

enter image description here

它确实意味着一些手动工作,但它会为您提供与已使用的缩放颜色不同的颜色。

你需要自己处理一个传奇(可能最简单的gridExtra),但你可以很好地控制颜色。