0
votes

I have created a chart in ggplot2 using data from the gapminder package in RStudio. I am curious how to convert the horizontal axis to log scale. I did use the function scale_x_continuous but after running the code the graph disappears.

ggplot(data = gapminder07) + geom_point(mapping = aes(x = gdpPercap, y = lifeExp))
p <- ggplot(gapminder07, aes(x = gdpPercap, y=lifeExp, label = country))
p + geom_text()
p + scale_x_continuous(trans = 'log10')

Edit* The same issue occurs when adding a fitted line. The line appears but the data points disappear.

ggplot(data = gapminder07) + geom_point(mapping = aes(x = gdpPercap, y = lifeExp))
p <- ggplot(gapminder07, aes(x = gdpPercap, y=lifeExp, label = country))
p + geom_text()
p + geom_smooth()
1

1 Answers

0
votes

You created a ggplot object with your first ggplot() call, and then you stored your second ggplot object into the variable p. In your next line, when you called p + geom_text(), you overwrite the first ggplot object with your second ggplot object with just geom_text().

Essentially, you called this code:

ggplot(data = gapminder07) + geom_point(mapping = aes(x = gdpPercap, y = lifeExp))
ggplot(gapminder07, aes(x = gdpPercap, y=lifeExp, label = country)) + geom_text()
ggplot(gapminder07, aes(x = gdpPercap, y=lifeExp, label = country)) + scale_x_continuous(trans = 'log10')

Each time you call p + ..., you overwrite the previous plot. Instead, you should do something like...

ggplot(gapminder::gapminder, aes(x = gdpPercap, y = lifeExp, color = country)) + geom_point() + scale_x_continuous(trans = 'log10')

I removed the geom_text() call since the countries' names just covered up the entire plot. I got this figure after running that code.