【问题标题】:Reverse color palette with legend limits ggplot2带有图例限制的反向调色板ggplot2
【发布时间】:2017-01-16 10:35:55
【问题描述】:

我有一组多边形,这是this问题中代码的可重现示例:

# polygons
square <- t(replicate(8, {
o <- runif(2)
c(o, o + c(0, 0.1), o + 0.1, o + c(0.1, 0), o)
}))
ID <- paste0('sq', seq_len(nrow(square)))

# Create SP
polys <- SpatialPolygons(mapply(function(poly, id) {
xy <- matrix(poly, ncol=2, byrow=TRUE)
Polygons(list(Polygon(xy)), ID=id)
}, split(square, row(square)), ID))

# Create SPDF and add a column for values
polys.df <- SpatialPolygonsDataFrame(polys, data.frame(id=ID, row.names=ID))
polys.df@data$number <- c(1,2,3,4,5,6,7,8)

然后我想用一个单一的调色板来绘制这些,但希望最高的数字是暗的,而不是默认的亮的。强化后使用ggplot

f.polys = fortify(polys.df, region='id')
f.polys = merge(f.polys, polys.df@data, by.x='id', by.y='id')   

我尝试使用几个 scale_fill_distiller 选项进行绘图。因此,此代码可用于设置图例栏限制,但不会反转调色板:

ggplot() + 
geom_polygon(data = f.polys, aes(x = long, y = lat, fill=number, group = group), color = 'black') + 
scale_fill_distiller(palette = "Oranges", limits = c(0,10), breaks=c(0,2,8))

并且此代码反转调色板,无法分配限制和中断:

ggplot() + 
geom_polygon(data = f.polys, aes(x = long, y = lat, fill=number, group = group), color = 'black') +
scale_fill_distiller(palette = "Oranges", trans = 'reverse')

当我尝试组合 scale_fill_distiller 参数时,调色板不会反转并且我丢失了比例尺。有什么建议吗?

ggplot() + 
geom_polygon(data = f.polys, aes(x = long, y = lat, fill=number, group = group), color = 'black') +
scale_fill_distiller(palette = "Oranges", trans = 'reverse',limits = c(0,10), breaks=c(0,2,8))

【问题讨论】:

  • 请包含您在示例代码中使用的任何额外包,以使示例可重现。

标签: r ggplot2 colors


【解决方案1】:

您需要切换您的limits,以便范围从高到低而不是从低到高。然后这匹配比例的反转并绘制图例。

scale_fill_distiller(palette = "Oranges", trans = "reverse", 
                 limits = c(10,0), breaks=c(0,2,8))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-04
    • 2014-07-13
    • 1970-01-01
    • 2020-07-07
    • 2017-12-05
    • 2017-04-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多