Ivan Cereghetti
Ivan Cereghetti

Reputation: 300

geom_text in the right of a heatmap in ggplot

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)

enter image description here

I would like to add a geom_text at the right of the last year of each country, so I can show 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")
)

Upvotes: 2

Views: 158

Answers (1)

Gregor Thomas
Gregor Thomas

Reputation: 145860

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

Upvotes: 3

Related Questions