geom_text in the right of a heatmap

Hi there! I created a heatmap with this dataframe:

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)

image

I would like to add a geom_text at the right of the last year of each country, that shows the counts how many red squares each country has. I think geom_text would be good, but i am not sure about how to create one for each country.

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")
)

There is an interesting answer here (second answer, not the accepted one).

datos %>%
  left_join(text, by="country_name") %>%
  ggplot(aes(x=year,y=country_name,fill=factor(crec), label=label)) + 
  geom_tile(color="grey",size=0.01)+
  scale_fill_manual(values=colors)+
  guides(fill=FALSE) +
  geom_text(x = 3.8,
            hjust = 0) +
  coord_cartesian(xlim = c(1,4), # This focuses the x-axis on the range of interest
                  clip = 'off') +
  theme_minimal()

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.