gpt4 book ai didi

r - 如何在ggplot2中创建具有大量值的点图

转载 作者:行者123 更新时间:2023-12-01 13:30:55 25 4
gpt4 key购买 nike

我创建了一个条形图来显示越南的人口分布。这是我的 vietnam2015数据:

 Year Age.group Est.pop
1 2015 0-4 7753
2 2015 5-9 7233
3 2015 10-14 6623
4 2015 15-19 6982
5 2015 20-24 8817
6 2015 25-29 8674
7 2015 30-34 7947
8 2015 35-39 7166
9 2015 40-44 6653
10 2015 45-49 6011
11 2015 50-54 5469
12 2015 55-59 4623
13 2015 60-64 3310
14 2015 65-69 1896
15 2015 70-74 1375
16 2015 75-79 1162
17 2015 80+ 1878

这是我的条形图,我想知道我是否也可以制作点图而不是条形图。
Library(tidyverse)

vietnam2015 %>%
filter(Age.group != "5-9") %>% # Somehow this weird value creeped into the data frame, is therefor filtered out.
ggplot(aes(x = Age.group, y = Est.pop)) +
geom_col(colour = "black",
fill = "#FFEB3B")

enter image description here

现在我知道点图通常用于没有那么多数据点的数据。但是我可以创建一个点图,其中一个点代表 1000 人或 100 万人吗?我喜欢更好地传达酒吧是由人组成的。像流数据的示例和中间图像:

Histogram explained

最佳答案

我们可以使用 geom_dotplot .正如您提到的,点图通常用于小计数,但我们可以汇总数据。在下面的代码中,我使用了 mutate(Est.pop = round(Est.pop, digits = -3)/1000)Est.pop到千,然后除以 1000。之后,我重复每个 Age.group我刚刚在 Est.pop 中计算了多少次柱子。最后,我使用了geom_dotplot绘制数据。每个点代表1000人。 y 轴是隐藏的,因为我认为这个可视化主要关注点数。

# Load package
library(tidyverse)

# Process the data
dt2 <- dt %>%
mutate(Est.pop = round(Est.pop, digits = -3)/1000) %>%
split(f = .$Age.group) %>%
map_df(function(x) x[rep(row.names(x), x$Est.pop[1]), ])

# Plot the data
ggplot(dt2, aes(x = Age.group)) +
geom_dotplot() +
scale_y_continuous(NULL, breaks = NULL)

enter image description here

数据
dt <- read.table(text = " Year Age.group Est.pop
1 2015 0-4 7753
2 2015 5-9 7233
3 2015 10-14 6623
4 2015 15-19 6982
5 2015 20-24 8817
6 2015 25-29 8674
7 2015 30-34 7947
8 2015 35-39 7166
9 2015 40-44 6653
10 2015 45-49 6011
11 2015 50-54 5469
12 2015 55-59 4623
13 2015 60-64 3310
14 2015 65-69 1896
15 2015 70-74 1375
16 2015 75-79 1162
17 2015 80+ 1878 ",
header = TRUE, stringsAsFactors = FALSE)

关于r - 如何在ggplot2中创建具有大量值的点图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45989074/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com