在geom_tile图上绘制geom_scatterpie

时间:2017-08-04 10:22:50

标签: r plot ggplot2 pie-chart tile

我想在geom_tile图表上使用geom_scatterpie绘制饼图。但是,我收到了一个错误:

Error: Discrete value supplied to continuous scale

这是我无法工作的简单代码:

library(ggplot2)
library(scatterpie)

nasafile <- "http://eosweb.larc.nasa.gov/sse/global/text/global_radiation"
nasa <- read.table(file=nasafile, skip=13, header=TRUE)

p <- ggplot(aes(y = Lat , x = Lon), data = nasa )+
      geom_tile(aes(fill=Ann)) +
      scale_fill_gradientn(colours=brewer.pal('YlOrRd', n=9)) +
      theme_bw() +
      coord_equal()
plot(p)

这样可行,但如果我在其上添加geom_scatterpie

首先绘制饼图的数据:

d <- data.frame(x=rnorm(5), y=rnorm(5))
d$A <- abs(rnorm(5, sd=1))
d$B <- abs(rnorm(5, sd=2))
d$C <- abs(rnorm(5, sd=3))

但是当我这样做时我得到了错误:

p + geom_scatterpie(aes(x=x, y=y), data=d, cols=c("A", "B", "C")) + coord_fixed()

1 个答案:

答案 0 :(得分:2)

The problem is that your geom_tile uses a continuous fill scale while geom_scatterpie uses a discrete fill scale. It works if you change Ann to a factor. Not ideal, but this works:

nasa$Ann <- as.factor(as.integer(nasa$Ann))
mypalette <- brewer.pal(9, "YlOrRd") # 6 for geom_tile, 3 for geom_scatterpie
p <- ggplot(aes(y = Lat , x = Lon), data = nasa )+
    geom_tile(aes(fill=Ann)) +
    scale_fill_manual(values = mypalette) +
    theme_bw() +
    coord_equal()
p

d <- data.frame(x=rnorm(5, 0, 50), y=rnorm(5, 0, 30))    # larger sd
d$A <- abs(rnorm(5, sd=1))
d$B <- abs(rnorm(5, sd=2))
d$C <- abs(rnorm(5, sd=3))

p + geom_scatterpie(aes(x=x, y=y, r = 20), data=d, cols=c("A", "B", "C"))  #larger radius

Or, using, size= instead of fill= (and no geom_scatterpie):

p <- ggplot(aes(y = Lat , x = Lon), data = nasa )+
    geom_tile(aes(fill=Ann)) +
    scale_fill_gradientn(colours=brewer.pal('YlOrRd', n=9)) +
    theme_bw() +
    coord_equal()
p

d <- data.frame(Lon = c(-100, 0, 100),
                Lat = c(-50, 0, 50),
                genvar = c(.1, .3, .5))

p + geom_point(data = d, aes(x = Lon, y = Lat, size = genvar),
               color = "white")