gpt4 book ai didi

带有图例限制的反向调色板ggplot2

转载 作者:行者123 更新时间:2023-12-05 03:10:33 24 4
gpt4 key购买 nike

我有一组多边形,一个来自 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))

enter image description here

这段代码反转了调色板,但无法分配限制和中断:

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

enter image description here

当我尝试组合 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))

enter image description here

最佳答案

您需要切换您的限制,使范围从高到低而不是从低到高。然后,这与比例的反转相匹配,并绘制了图例。

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

关于带有图例限制的反向调色板ggplot2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39391872/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com