What type of graph is this? And can it be created using ggplot2?

Viewed 172

I have this chart that I'm attempting to replicate. It has two continuous variables for the X & Y axes, and charts the relationship between these two variables through time with a line.

My question has two parts:

  • First, what is this type of chart called? It is unusual because the line between the points is determined by a third variable (the year) rather than their positions on the X axis.

  • Second, does anyone know whether this can be achieved with ggplot? I have so far created a chart similar to the above but without the line connecting the points. This code ggplot(data, aes(x = Weekly_Hours_Per_Person, y = GDP_Per_Hour)) + geom_point() has gotten the below output: enter image description here But how to get the line over years?

Any help on either point will be appreciated. Thanks!

2 Answers

Use geom_path, i.e.

libraray(ggplot2)
ggplot(data, aes(x = Weekly_Hours_Per_Person, y = GDP_Per_Hour)) +
geom_point() + 
geom_path()

Just expanding upon the original question. This is a path graph, and as explained here:

"geom_path() connects the observations in the order in which they appear in the data. geom_line() connects them in order of the variable on the x axis."

As an extension of your original question, you can label selected points where the line bends. Here is an example with reproducible data:

set.seed(123)
df <- data.frame(year = 1960:2006,
           Weekly_Hours_Per_Person = c(2:10, 9:0, 1:10, 9:1, 2:10),
           GDP_Per_Hour = 1:47 + rnorm(n = 47, mean = 0))

# Only label selected years
df_label <- filter(df, year %in% c(1960, 1968, 1978, 1988, 1997, 2006))

And use the ggrepel package to offset the labels from the vertices.

library(ggrepel)

ggplot(df, aes(Weekly_Hours_Per_Person, GDP_Per_Hour)) +
  geom_path() +
  geom_point(data = df_label) +
  geom_text_repel(data = df_label, aes(label = year)) +
  scale_x_continuous(limits = c(-2, 12))
))

enter image description here

Related