我用这个数据框创建了一个热图:
datos<- data.frame(
stringsAsFactors = FALSE,
country_name = c("Argentina","Bolivia",
"Brazil","Chile","Colombia","Paraguay","Peru","Uruguay",
"Argentina","Bolivia","Brazil","Chile","Colombia",
"Paraguay","Peru","Uruguay","Argentina","Bolivia",
"Brazil","Chile"),
year = c("1961","1961","1961","1961",
"1961","1961","1961","1961","1962","1962","1962",
"1962","1962","1962","1962","1962","1963","1963",
"1963","1963"),
crec = c(1,1,1,1,1,1,1,1,0,1,1,
1,1,1,1,0,0,1,1,1)
)
colors<-c("red","blue")
chart<- ggplot(datos,aes(x=year,y=country_name,fill=factor(crec))) +
geom_tile(color=gris,size=0.01)+
scale_fill_manual(values=colors)+
scale_y_discrete(limits = crisis$country_name)+
guides(fill=FALSE)
我想在每个国家/地区去年的右侧添加一个 geom_text,这样我就可以显示每个国家/地区有多少个红色方 block 。我认为 geom_text 会很好,但我不确定如何为每个国家/地区创建一个。
text<- data.frame(
stringsAsFactors = FALSE,
country_name = c("Colombia","Bolivia","Chile",
"Peru","Brazil","Paraguay","Uruguay","Argentina"),
label = c("0 years","0 years","0 years",
"0 years","0 years","0 years","1 years","2 years")
)
最佳答案
library(dplyr)
# get the maximum year per country
text = text %>%
left_join(
datos %>% group_by(country_name) %>%
summarize(year = max(year))
)
chart +
geom_text(
data = text,
aes(label = label, x = year, y = country_name),
# left justified, but nudged to the right
hjust = 0, nudge_x = 0.55,
inherit.aes = FALSE
) +
# give a little extra room for the text
scale_x_discrete(expand = expansion(mult = 0, add = c(0, 1)))
关于r - ggplot 中热图右侧的 geom_text,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63362510/