gpt4 book ai didi

r - R : 99 icons instead of 100 icons 中的华夫饼图

转载 作者:行者123 更新时间:2023-12-05 03:17:36 35 4
gpt4 key购买 nike

数据如下:

df <- structure(list(country = c("Australia", "Australia", "Australia", 
"South Korea", "South Korea", "South Korea"), parts = c("case_1",
"case_2", "non_case", "case_1", "case_2", "non_case"), values = c(1,
19, 80, 1, 29, 70)), row.names = c(NA, -6L), class = c("tbl_df",
"tbl", "data.frame"))
library(tidyverse)
library(waffle)
df %>% ggplot(aes(label = parts, values = values)) +
geom_pictogram(n_rows = 10, aes(color = parts),
family = 'fontawesome-webfont',
flip = TRUE,
size = 6,
show.legend = FALSE,
make_proportional = TRUE
) +
scale_label_pictogram(
name = "Confirmed cases",
values = c("male"),
) +
coord_equal() +theme_minimal() +
facet_wrap(~country, nrow = 2, strip.position = "top")

在上面的代码中,我生成了下面的华夫饼图。使用 make_proportional = TRUEn_rows = 10,我预计每个国家/地区会获得 100 个图标,但韩国会得到 99 个。解决此问题的唯一方法是先计算所有比例并使用 make_proportional = FALSE,但这需要一些时间。另外,我觉得这有点奇怪。如果有人能帮助我,我将不胜感激。

enter image description here

最佳答案

waffle这个函数好像有个奇怪的舍入问题。根据documentationmake_proportional 参数执行以下操作:

compute proportions from the raw values? (i.e. each value n will bereplaced with n/sum(n)); default is FALSE.

值的四舍五入似乎出了问题。这是一个使用 as.integer 的演示,其中 n2 显示当前发生的情况,n3 是实际应该发生的值:

library(dplyr)
df %>%
group_by(country) %>%
mutate(n = values/sum(values)) %>%
ungroup() %>%
mutate(n2 = as.integer(n*100),
n3 = as.integer(round(n*100)))
#> # A tibble: 6 × 6
#> country parts values n n2 n3
#> <chr> <chr> <dbl> <dbl> <int> <int>
#> 1 Australia case_1 1 0.01 1 1
#> 2 Australia case_2 19 0.19 19 19
#> 3 Australia non_case 80 0.8 80 80
#> 4 South Korea case_1 1 0.01 1 1
#> 5 South Korea case_2 29 0.29 28 29
#> 6 South Korea non_case 70 0.7 70 70

创建于 2022-10-16 reprex v2.0.2

如您所见,它应该类似于 n3。因此,您可以做的是检查您的值与 n2 之间的差异是否大于 0,以便将您的值加 1 以获得所需的结果,如下所示:

library(waffle)
library(magrittr)
library(ggplot2)
library(dplyr)
library(emojifont)
library(waffle)
library(extrafont)
#> Registering fonts with R
df %>%
group_by(country) %>%
mutate(n = values/sum(values)) %>%
ungroup() %>%
mutate(n2 = as.integer(n*100)) %>%
mutate(values = ifelse(values-n2 > 0, values + 1, values)) %>%
ggplot(aes(label = parts, values = values)) +
geom_pictogram(n_rows = 10, aes(color = parts),
family = 'fontawesome-webfont',
flip = TRUE,
size = 6,
show.legend = FALSE,
make_proportional = TRUE
) +
scale_label_pictogram(
name = "Confirmed cases",
values = c("male"),
) +
coord_equal() +theme_minimal() +
facet_wrap(~country, nrow = 2, strip.position = "top")

创建于 2022-10-16 reprex v2.0.2

关于r - R : 99 icons instead of 100 icons 中的华夫饼图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74086119/

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