ggplot 将数据框作为其输入,并创建一个绘图对象,其中包含与生成它的所有参数相对应的许多片段。虽然从 ggplot 中提取数据在技术上是可行的,但它有点复杂,可能不会出现在介绍性会话中。 (请参阅底部的示例。)
基于我见过的其他 ggplot 教程(例如其创建者的 this one),更典型的做法是从显示数据框开始,并显示过滤该数据如何改变绘图。
这是一个应该有效的过程。如果它不适合您,请分享您收到的任何具体错误消息。
- 重新启动 R。如果您使用的是 RStudio,请单击会话 -> 重新启动 R。
- 加载库。这个例子至少使用了 ggplot2 和 gapminder,也许还有其他的。
library(ggplot2)
library(gapminder)
library(dplyr) # I think this is the source of the "filter" function used here
- 查看数据框。这是
gapminder 数据,它有 1,704 行。每个国家/地区的数据中每一年都有一行,例如 1952 年、1957 年等。
> gapminder
# A tibble: 1,704 x 6
country continent year lifeExp pop gdpPercap
<fct> <fct> <int> <dbl> <int> <dbl>
1 Afghanistan Asia 1952 28.8 8425333 779.
2 Afghanistan Asia 1957 30.3 9240934 821.
3 Afghanistan Asia 1962 32.0 10267083 853.
4 Afghanistan Asia 1967 34.0 11537966 836.
5 Afghanistan Asia 1972 36.1 13079460 740.
6 Afghanistan Asia 1977 38.4 14880372 786.
7 Afghanistan Asia 1982 39.9 12881816 978.
8 Afghanistan Asia 1987 40.8 13867957 852.
9 Afghanistan Asia 1992 41.7 16317921 649.
10 Afghanistan Asia 1997 41.8 22227415 635.
# … with 1,694 more rows
- 我们可以过滤到 1957 年的数据。(我不确定
group = 1 部分的用途 - 也许您的问题中没有提到更早的步骤?)
# Note: equivalent to `filter(gapminder, year == 1957)`
> filter(gapminder, gapminder$year == 1957)
# A tibble: 142 x 6
country continent year lifeExp pop gdpPercap
<fct> <fct> <int> <dbl> <int> <dbl>
1 Afghanistan Asia 1957 30.3 9240934 821.
2 Albania Europe 1957 59.3 1476505 1942.
3 Algeria Africa 1957 45.7 10270856 3014.
4 Angola Africa 1957 32.0 4561361 3828.
5 Argentina Americas 1957 64.4 19610538 6857.
6 Australia Oceania 1957 70.3 9712569 10950.
7 Austria Europe 1957 67.5 6965860 8843.
8 Bahrain Asia 1957 53.8 138655 11636.
9 Bangladesh Asia 1957 39.3 51365468 662.
10 Belgium Europe 1957 69.2 8989111 9715.
# … with 132 more rows
- 将过滤后的数据发送到 ggplot。
ggplot 函数的第一项代表输入数据。 (我在这里省略了“group = 1”,因为我不知道它是在哪里定义的。那部分可能实际上属于aes(...) 部分吗?group = 1 有时在我们希望 ggplot 提供某种统计信息时在那里使用我们希望它将整个数据集视为一组,例如,如果您想要所有国家/地区的平均 gdp,而不是按大陆的单独平均值...)
ggplot(filter(gapminder, gapminder$year==1987)) +
geom_point(aes(gdpPercap, lifeExp, color=continent, size=pop)) +
xlab("GDP per capita") +
ylab("Life expectancy at birth")
这是我得到的输出。有什么问题吗?
从 ggplot 对象中提取数据。
这是相同的情节,分配给名为gg的对象:
gg <- ggplot(filter(gapminder, gapminder$year==1987)) +
geom_point(aes(gdpPercap, lifeExp, color=continent, size=pop)) +
xlab("GDP per capita") +
ylab("Life expectancy at birth")
那个 gg 对象结合了许多组件。在 RStudio 中,您可以检查它们并以交互方式提取组件。其中之一是源数据:
> gg[["data"]]
# A tibble: 142 x 6
country continent year lifeExp pop gdpPercap
<fct> <fct> <int> <dbl> <int> <dbl>
1 Afghanistan Asia 1987 40.8 13867957 852.
2 Albania Europe 1987 72 3075321 3739.
3 Algeria Africa 1987 65.8 23254956 5681.
4 Angola Africa 1987 39.9 7874230 2430.
5 Argentina Americas 1987 70.8 31620918 9140.
6 Australia Oceania 1987 76.3 16257249 21889.
7 Austria Europe 1987 74.9 7578903 23688.
8 Bahrain Asia 1987 70.8 454612 18524.
9 Bangladesh Asia 1987 52.8 103764241 752.
10 Belgium Europe 1987 75.4 9870200 22526.
# … with 132 more rows