r - ggplot 中热图右侧的 geom_text

标签 r

我用这个数据框创建了一个热图:

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)

enter image description here

我想在每个国家/地区去年的右侧添加一个 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)))

enter image description here

关于r - ggplot 中热图右侧的 geom_text,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63362510/

相关文章:

ROCR 错误 : Format of predictions is invalid

r - 如何使用 r 中的plot() 在 x 轴上创建具有有序字符变量的散点图?

R 粘贴列表进行绑定(bind)

r - 无法在 RStudio 中启动 SparkR

r - 如果 R 数据框中的列包含特定文本,则删除重复的观察值

r - 将两列值折叠到新列中

R structchange RSS 和 BIC 用于一个断点

r - 编辑 Excel 工作表的特定单元格

r - 在 R 中使用 Paste() 创建函数名称

database - R tm : reloading a 'PCorpus' backend filehash database as corpus (e. g。在重新启动的 session /脚本中)