英文:
How to add count labels to statebin map?
问题
以下代码创建了一个 statbin 热图。我们如何在每个 bin 上添加包含计数的标签?(所需标签已经准备在数据的 lab
列中。)
library(statebins)
dat = data.frame(state = state.abb, val = rep(0:24, 2))
dat$lab = paste(dat$state, dat$val, sep = "\n")
head(dat)
# state val lab
# 1 AL 0 AL\n0
# 2 AK 1 AK\n1
# 3 AZ 2 AZ\n2
# 4 AR 3 AR\n3
# 5 CA 4 CA\n4
# 6 CO 5 CO\n5
sb = statebins(dat, state_col = "state", value_col = "val") +
theme_statebins()
sb
英文:
The following code creates a statbin heatmap. How can we add labels with the counts to each bin? (Desired labels have been prepared in the lab
column of the data.)
library(statebins)
dat = data.frame(state = state.abb, val = rep(0:24, 2))
dat$lab = paste(dat$state, dat$val, sep = "\n")
head(dat)
# state val lab
# 1 AL 0 AL\n0
# 2 AK 1 AK\n1
# 3 AZ 2 AZ\n2
# 4 AR 3 AR\n3
# 5 CA 4 CA\n4
# 6 CO 5 CO\n5
sb = statebins(dat, state_col = "state", value_col = "val") +
theme_statebins()
sb
答案1
得分: 1
我们可以直接像这样编辑构建好的绘图中的geom_text
标签,确保与正确的顺序匹配:
library(ggplot2)
sb = ggplot_build(sb)
sb$data[[2]]$label = dat$lab[match(sb$data[[2]]$label, dat$state)]
sb = ggplot_gtable(sb)
plot(sb)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论