[英]Customize how R tmap legend values are printed
有没有办法自定义 R tmap 图例值的打印方式? 代替:
...我想实现以下分类,以避免打印两次相同的值:
248-500
50 1 -1000 (501 而不是 500)
100 1 -10000 (1001 而不是 1000)
1000 1 -20000 (10001 而不是 10000)
2000 1 -21588 (20001 而不是 20000)
此外,我想将所有“-”打印在彼此的正下方,以便所有十、百和千值都可以轻松进行比较。 这张图片说明了我想要达到的结果:
这是我的示例代码,它尚未工作:
library(sf)
library(tmap)
mybreaks1 = c(248, 500, 1000, 10000, 20000, 21588)
mybreaks2 = c()
for (i in 1:length(mybreaks1)-1){
print(i)
if (i == 1){
mybreaks2[i] <- paste0(mybreaks1[i], " - ", mybreaks1[i+1])
}
if (i >1){
mybreaks2[i] <- paste0(mybreaks1[i]+1, " - ", mybreaks1[i+1])
}
}
mybreaks2
nc <- st_read(system.file("shape/nc.shp", package="sf"))
myplot <- tm_shape(nc) +
tm_fill("BIR74",
palette="Set1", # tmaptools::palette_explorer()
style="fixed",
breaks= mybreaks) +
tm_borders(
col = "grey40",
lwd = 1,
lty = "solid",
alpha = NA) +
tm_layout(
legend.show = TRUE,
frame = FALSE,
legend.outside = TRUE,
legend.position = c("right","top")
#legend.just = "middle",
#legend.format=list(fun=function(x) formatC(x, digits=0, format="d"), text.separator= "-", text.align = "left")
) +
tm_add_legend(labels= mybreaks2, col = c("red", "orange", "green", "blue", "purple"))
myplot
要详细说明@orlando-sabogal 的答案 - 因为问题包括图例居中和数千人的分离 - 考虑以下代码:
它使用包括图例文本的居中(尽管小破折号没有完全对齐;你需要一个固定宽度的字体),并将prettyNum()
应用于图例以清楚地分隔数千个。
如果您遵循美国(而非欧洲)编号约定,请随意替换空格:)
library(tmap)
library(sf)
mybreaks1 = c(248, 500, 1000, 10000, 20000, 21588)
mybreaks2 = c()
for (i in 1:length(mybreaks1)-1){
print(i)
if (i == 1){
mybreaks2[i] <- paste0(mybreaks1[i], " - ", mybreaks1[i+1])
}
if (i >1){
mybreaks2[i] <- paste0(prettyNum(mybreaks1[i]+1, big.mark = " "), " - ", prettyNum(mybreaks1[i+1], big.mark = " "))
}
}
mybreaks2
nc <- st_read(system.file("shape/nc.shp", package="sf"))
myplot <- tm_shape(nc) +
tm_fill("BIR74",
palette="Set1", # tmaptools::palette_explorer()
style="fixed",
breaks= mybreaks1,
labels = mybreaks2) +
tm_borders(
col = "grey40",
lwd = 1,
lty = "solid",
alpha = NA) +
tm_layout(
legend.show = TRUE,
frame = FALSE,
legend.outside = TRUE,
legend.format = list(text.align = "center"),
legend.position = c("right","top"))
myplot
我认为您的问题是您在 tm_add_legend() 函数中而不是在 tm_fill() 函数中包含了break2标签。
我认为以下是您需要的:
mybreaks1 = c(248, 500, 1000, 10000, 20000, 21588)
mybreaks2 = c()
for (i in 1:length(mybreaks1)-1){
print(i)
if (i == 1){
mybreaks2[i] <- paste0(mybreaks1[i], " - ", mybreaks1[i+1])
}
if (i >1){
mybreaks2[i] <- paste0(mybreaks1[i]+1, " - ", mybreaks1[i+1])
}
}
mybreaks2
nc <- st_read(system.file("shape/nc.shp", package="sf"))
myplot <- tm_shape(nc) +
tm_fill("BIR74",
palette="Set1", # tmaptools::palette_explorer()
style="fixed",
breaks= mybreaks1,
labels = mybreaks2) +
tm_borders(
col = "grey40",
lwd = 1,
lty = "solid",
alpha = NA) +
tm_layout(
legend.show = TRUE,
frame = FALSE,
legend.outside = TRUE,
legend.position = c("right","top"))
myplot
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.