添加颜色aestethic ggplot + ggmap后,整个地图变为红色

时间:2015-08-25 17:09:31

标签: r ggplot2

我尝试将colour aestethic添加到stat_summary_hex,之后,我的ggmap全部变为红色。其他一切正常。

代码

map.querySold  <- function(return.query) {

  # Specify target destination vo = vänstra övre , hu = högra undre
  vo.lon  <- min(return.query$location.position.longitude)
  vo.lat  <- max(return.query$location.position.latitude)

  hu.lon  <- max(return.query$location.position.longitude)
  hu.lat  <- min(return.query$location.position.latitude)

  # Set map 
  map <- get_map(location=c(vo.lon, vo.lat, hu.lon, hu.lat), zoom= 11, maptype = "roadmap", color = "bw")

  # Create map
  ggmap(map) + 
    stat_summary_hex(data = return.query, aes(x = location.position.longitude, y = location.position.latitude, z = sqrmPrice, colour = sqrmRent), alpha = 0.5 , fun = mean) +
    scale_fill_gradient(name = "Average sold sqrm-price", low = 'green', high = 'red') +
    theme_hl()

}

数据

 sqrmRent sqrmPrice location.position.longitude location.position.latitude
1  (50,100]  26373.63                    17.84024                   59.37254
2  (50,100]  38321.17                    18.03322                   59.26387
3 (100,150]  78913.04                    17.98254                   59.29965
4  (50,100]  51630.43                    17.93659                   59.34115
5  (50,100]  51000.00                    18.01421                   59.30183
6  (50,100]  76161.62                    18.00596                   59.33852

用颜色aestethic on enter image description here

上没有颜色aestethic

enter image description here

按要求

table(return.query $ sqrmRent)

> table(return.query$sqrmRent)

       [0,50]  (50,100] (100,150] (150,200] (200,250] 
        13939     23898        51         1         0 

链接到整个return.query数据

http://www.filedropper.com/stackoverflow_1

1 个答案:

答案 0 :(得分:4)

查看ggplot_build的输出,看起来数据首先按y值排序,在本例中为location.position.latitude。因此,您可以以相同的方式对sqrmRent进行排序,并在aes调用之外通过该变量为其设置颜色。请注意,排序似乎是y,然后是x,所以如果有共享y值的数据点,则需要按x值对它们进行二次排序。这不仅仅是一个正确的解决方案,而是添加标签,您可以添加由geom_line着色的虚拟geom(此处sqrmRent)。

  ggmap(map) +
    stat_summary_hex(data = return.query, aes(x = location.position.longitude,
                         y = location.position.latitude, z = sqrmPrice),
                     color=return.query$sqrmRent[order(return.query$location.position.latitude)],
                     alpha=0.5, fun = mean) +
    scale_fill_gradient(name = "Average sold sqrm-price", low = 'green', high = 'red') +
    geom_line(data=return.query, aes(x=1, y=1, color=sqrmRent)) +
    scale_color_manual(values=1:2, labels=levels(return.query$sqrmRent))

enter image description here