2

I've been trying to gain some experience with ggplot2 using Kieran Healy's excellent online book as a starting point, but I've run into a quirk I can't figure out. Using Gapminder data, I'm trying to create a scatterplot showing life expectancy vs GDP per capita. I'd like to include two years of data, distinguishing the years using both color and shape. Finally, I would like to label an outlier, Kuwait in 1952.

I know I could use annotate to do this manually, but I was hoping someone might have a more elegant solution. In addition, I'd love to know why this code, which seems perfectly legitimate to this novice, is not working the way it seems it should. Thanks very much!

library(ggplot2)
library(gapminder)
gap <- subset(gapminder,year==min(year) | year==max(year))
gap$year <- as.character(gap$year)
p <- ggplot(data = gap,
            mapping = aes(y = lifeExp,
                          x = gdpPercap,
                          col = year))
p + geom_point(aes(shape=year)) + theme_classic() +
  scale_x_log10(labels=scales::dollar) +
  geom_text_repel(data=subset(gap,gdpPercap>100000),
                  mapping=aes(label=country)) +
  labs(title="Life expectancy by output per capita",
       y="",x="GDP per capita")
  • 4
    To my opinion, everything looks right on your code. Did you load the library `ggrepel` ? I would just add `show.legend = FALSE` in `geom_text_repel` but on my r session, everything is working fine. – dc37 Apr 25 '20 at 05:33
  • 2
    Is an `'a'` in the legend the problem? If yes then this is a [duplicate](https://stackoverflow.com/questions/18337653/remove-a-from-legend-when-using-aesthetics-and-geom-text). – Rui Barradas Apr 25 '20 at 05:52
  • Yes, adding show.legend = FALSE did the trick. I hadn't recognized the change in the legend as the addition of a letter "a," but Rui is correct and it appears that the linked question also provides some useful information. Thanks for your help! – NedFlanders Apr 26 '20 at 03:32

1 Answers1

1

I personally prefer using annotate for annotation, because you won't have exactly this type of surprises that you have with using a geom. Also, geoms tend to draw for each row of your data frame, so this may create some ugly effects on the fonts/ shapes.

library(ggplot2)
library(ggrepel)
library(gapminder)
gap <- subset(gapminder,year==min(year) | year==max(year))
gap$year <- as.character(gap$year)

ggplot(data = gap, aes(y = lifeExp, x = gdpPercap, col = year)) +
  geom_point(aes(shape=year)) + 
  theme_classic() +
  scale_x_log10(labels=scales::dollar) +
  annotate(geom = "label_repel", 
           x = gap$gdpPercap[gap$gdpPercap>100000], 
           y = gap$lifeExp[gap$gdpPercap>100000],
           label = gap$country[gap$gdpPercap>100000]) 

Created on 2020-04-25 by the reprex package (v0.3.0)

tjebo
  • 21,977
  • 7
  • 58
  • 94