问题描述
我正在尝试反转R中我的leaflet
图例的值显示.此涵盖了分类数据,但是我正在处理连续数据.这是一个玩具示例:
I am trying to reverse the value display of my leaflet
legend in R. This post covers categorical data, but I am working with continuous data. Here's a toy example:
map <- leaflet() %>% addProviderTiles('Esri.WorldTopoMap')
x <- 1:100
pal <- colorNumeric(c("#d7191c","#fdae61","#ffffbf","#abd9e9", "#2c7bb6"), x)
map %>% addLegend('topright', pal=pal, values=x)
我希望图例在顶部读取100,在底部读取1,并且颜色反转.我当然可以颠倒colorNumeric()
中的颜色,但是颠倒标签的顺序会更困难.我试图反转x
中值的顺序,甚至为addLegend()
摆弄了labelFormat()
参数,以引用反转值的查找表……似乎没有任何作用.有没有简单的方法可以做到这一点?
I'd like the legend to read 100 at the top and 1 on the bottom with the colors reversed. I can certainly reverse the colors in colorNumeric()
, but reversing the order of the labels is harder. I have tried reversing the order of the values in x
, and I even fiddled with the labelFormat()
parameter for addLegend()
to reference a lookup table of reversed values... nothing seems to work. Is there an easy way to do this?
推荐答案
不幸的是,对此的公认答案将使数字与它们表示的颜色不一致(实际上完全相反).
Unfortunately the accepted answer to this will get the numbers out of alignment (in fact exactly reversed) from the colours they represent.
这是最初提出的解决方案,我说这是不正确的:
Here's the original proposed solution, which I say is incorrect:
map <- leaflet() %>% addProviderTiles('Esri.WorldTopoMap')
x <- 1:100
pal <- colorNumeric(c("#d7191c","#fdae61","#ffffbf","#abd9e9", "#2c7bb6"), x)
map %>% addLegend('topright', pal=pal, values=x)
# This solution shows 100 as red
map %>% addLegend('topright',
pal = pal,
values = x,
labFormat = labelFormat(transform = function(x) sort(x, decreasing = TRUE)))
但是,如果您一直使用pal()
函数在地图上绘制任何内容,那么现在您就完全错了.
But if you've been using the pal()
function to draw anything on your map, you now have it exactly wrong.
# But 100 is blue, not red
plot(1, 1, pch = 19, cex = 3, col = pal(100))
我认为解决方案是将函数定义为将颜色分配给数字,一种用于图例相反,一种用于实际绘制事物:
I think the solution is to define to functions that allocate colours to numbers, one in reverse for the legend, and one for actually drawing things:
pal_rev <- colorNumeric(c("#d7191c","#fdae61","#ffffbf","#abd9e9", "#2c7bb6"), x, reverse = TRUE)
map %>% addLegend('topright',
pal = pal_rev,
values = x,
labFormat = labelFormat(transform = function(x) sort(x, decreasing = TRUE)))
这为我们提供了一个与我们将要绘制的内容相匹配的图例,即100现在可以正确显示为蓝色:
This gives us a legend that matches anything we will have drawn ie 100 is now correctly shown to be blue:
这篇关于R传单连续图例中的逆序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!