这是什么类型的图表?能用ggplot2创建吗?

5

我有一个图表想要复制。它有两个连续变量用于X和Y轴,并通过一条线来展示这两个变量之间的关系随时间的变化。

我的问题有两个部分:

  • 首先,这种类型的图表叫什么?它很不寻常,因为连接点之间的线是由第三个变量(年份)确定的,而不是它们在X轴上的位置。

  • 其次,有人知道是否可以使用ggplot实现这一点吗?到目前为止,我已经创建了一个类似于上面的图表,但没有连接点之间的线。 这段代码 ggplot(data, aes(x = Weekly_Hours_Per_Person, y = GDP_Per_Hour)) + geom_point() 已经得到了下面的输出: enter image description here 但如何获得跨年的线条?

任何关于这两个问题的帮助都将不胜感激。谢谢!

2个回答

7
使用geom_path,即:
libraray(ggplot2)
ggplot(data, aes(x = Weekly_Hours_Per_Person, y = GDP_Per_Hour)) +
geom_point() + 
geom_path()

4

我将扩展原始问题。这是一条路径图,如此处所述:

"geom_path()按照数据中出现的顺序连接观察值。geom_line()按照x轴上的变量顺序连接它们。"

作为原始问题的扩展,您可以标记折线弯曲的位置。以下是一个可重复使用的数据示例:

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))

使用ggrepel包使标签与顶点偏离。

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接