Label lines with ggplot

Hi there! I have a datarame like this:

datos[1:20,]
# A tibble: 20 x 4
  country_name country_code year  value
1 Argentina    ARG          1990  1    
2 Bolivia      BOL          1990  1    
3 Brazil       BRA          1990  1    
4 Chile        CHL          1990  1    
5 Colombia     COL          1990  1    
6 Ecuador      ECU          1990  1    
7 Paraguay     PRY          1990  1    
8 Peru         PER          1990  1    
9 Uruguay      URY          1990  1    
10 Argentina    ARG          1991  1.08 
11 Bolivia      BOL          1991  1.03 
12 Brazil       BRA          1991  0.997
13 Chile        CHL          1991  1.06 
14 Colombia     COL          1991  1.00 
15 Ecuador      ECU          1991  1.02 
16 Paraguay     PRY          1991  1.01 
17 Peru         PER          1991  1.00 
18 Uruguay      URY          1991  1.03 
19 Argentina    ARG          1992  1.15 
20 Bolivia      BOL          1992  1.03 

I want to create a chart for each country with a label to identify all of them.

ggplot(datos,aes(x=year,y=value,group=country_name, color = 
country_name,label=country_name)) + 
  geom_line() + 
  geom_point()+
  geom_text(data = datos, 
                   aes(label = country_name, color = country_name, hjust = -1, vjust = 1)) 

My result has a label for each point of each line There is any way I can only have a label for each line?:

1 Like

You need to filter the data passed to geom_text so that it has only one row per country. One way would be to put the label at the end of each country line. Something like this:

geom_text(data = . %>% group_by(country_name) %>% filter(year==max(year)), 
          nudge_x=0.1, hjust=0) +
expand_limits(x = max(datos$year) + 2) +
guides(colour=FALSE)

The . is a "pronoun" that refers back to the data frame the was already provided in the main ggplot call. We modify the data to keep only the last year for each country.

You don't need to repeat the aes() inside geom_text, since you already have the aesthetics in the main call to ggplot.

expand_limits is there to add space to the right of the data lines in order to make room for the country labels. You might need to adjust the amount of space added.

Since the countries are directly labeled, there's no need for a legend, so I've removed it.

3 Likes

You are amazing!! Thank you so much!

1 Like

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