gpt4 book ai didi

r - geom_waffle 不显示一个单元格

转载 作者:行者123 更新时间:2023-12-05 01:54:50 26 4
gpt4 key购买 nike

我一直在使用 waffle 包,但我无法解决如何修复此华夫饼图以使其显示 100 个正方形/单元格

Waffle plot

这是数据和我的代码:

# devtools::install_github("hrbrmstr/waffle")
library(ggplot)
library(waffle)

data <- structure(list(greenfield = c(0, 1), n = c(162L, 399L), total_investments = c(561,
561), percentage = c(28.8770053475936, 71.1229946524064), name_greenfield = c("M&A",
"Greenfield")), row.names = c(NA, -2L), groups = structure(list(
greenfield = c(0, 1), .rows = structure(list(1L, 2L), ptype = integer(0), class = c("vctrs_list_of",
"vctrs_vctr", "list"))), row.names = c(NA, -2L), class = c("tbl_df",
"tbl", "data.frame"), .drop = TRUE), class = c("grouped_df",
"tbl_df", "tbl", "data.frame"))

# Waffle plot

ggplot(data,
aes(fill = name_greenfield,
values = percentage)) +
coord_equal() +
geom_waffle(size = 0.31,
flip = T,
make_proportional = T,
height = 0.9, width = 0.9,
color = "white") +
coord_equal() +
theme_ipsum_rc(grid="",
plot_title_face = "plain",
plot_title_size = 14,
plot_title_margin = 0) +
theme_enhance_waffle() +
labs(title = "Types of investments",
fill = "",
caption = "Source: Author's own elaboration") +
scale_fill_grey(start = 0.4, end = 0.7)

我还没有找到问题所在,如果有人能帮助我,我将不胜感激!

最佳答案

代码中存在一个非常非常奇怪的错误。这是我怀疑正在发生的事情。在 GitHub 上的源代码中,有一个文件 stat-waffle.R .在第 93 行你会发现:

if (params[["make_proportional"]]) {
.x[["values"]] <- .x[["values"]] / sum(.x[["values"]])
.x[["values"]] <- round_preserve_sum(.x[["values"]], digits = 2)
.x[["values"]] <- as.integer(.x[["values"]] * 100)
}

对于您的值(value)观,这里发生了一些非常奇怪的事情。

.x <- list(values = c(29, 71))

.x[["values"]] <- .x[["values"]] / sum(.x[["values"]])
# [1] 0.29 0.71
.x[["values"]] <- waffle:::round_preserve_sum(.x[["values"]], digits = 2)
# [1] 0.29 0.71
.x[["values"]] <- as.integer(.x[["values"]] * 100)
# [1] 28 71

这就是您看到缺少一个方 block 的原因。它与 float 学有关。

format(round(.x$values / sum(.x$values), 2) * 100, digits = 22)
# [1] "28.999999999999996" "71.000000000000000"

如果您进行此修改,结果将如预期。

.x[["values"]] <- as.integer(round(.x[["values"]] * 100))
# [1] 29 71

这对您意味着什么?提前将您的数字四舍五入为总和为 100 的整数,并使用 make_proportional = FALSE。这样代码块就不会运行。

data$percentage <- as.integer(round(round(data$percentage / sum(data$percentage), 2) * 100))
data$percentage
# [1] 29 71

ggplot(data,
aes(fill = name_greenfield,
values = percentage)) +
coord_equal() +
geom_waffle(size = 0.31,
flip = T,
make_proportional = FALSE,
height = 0.9, width = 0.9,
color = "white") +
coord_equal() +
theme_enhance_waffle() +
labs(title = "Types of investments",
fill = "",
caption = "Source: Author's own elaboration") +
scale_fill_grey(start = 0.4, end = 0.7)

这应该能满足您的期望。

waffle plot

关于r - geom_waffle 不显示一个单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70520851/

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