gpt4 book ai didi

带逗号但没有小数的 R 标签

转载 作者:行者123 更新时间:2023-12-02 00:04:11 25 4
gpt4 key购买 nike

我的目标是生成带有逗号但没有小数的标签。假设我有一个包含以下部分的 ggplot:

geom_text(aes(y = var,
label = scales::comma(round(var))), hjust = 0, nudge_y = 300 )

这几乎就是我所需要的。它给了我逗号,但有一个小数点。我在这里 ( axis labels with comma but no decimals ggplot ) 看到 comma_format() 可能不错,但我认为我的标签需要数据参数,而 comma_format() 不需要拿。我能做什么?

更新:

作为此问题何时发生的示例,请参阅以下内容,其中使用了 gganimate 并且还有很多其他问题。代码源自 Jon Spring 在 Animated sorted bar chart with bars overtaking each other 的回答

library(gapminder)
library(gganimate)
library(tidyverse)

gap_smoother <- gapminder %>%
filter(continent == "Asia") %>%
group_by(country) %>%
complete(year = full_seq(year, 1)) %>%
mutate(gdpPercap = spline(x = year, y = gdpPercap, xout = year)$y) %>%
group_by(year) %>%
mutate(rank = min_rank(-gdpPercap) * 1) %>%
ungroup() %>%
group_by(country) %>%
complete(year = full_seq(year, .5)) %>%
mutate(gdpPercap = spline(x = year, y = gdpPercap, xout = year)$y) %>%
mutate(rank = approx(x = year, y = rank, xout = year)$y) %>%
ungroup() %>%
arrange(country,year)

gap_smoother2 <- gap_smoother %>% filter(year<=2007 & year>=1999)
gap_smoother3 <- gap_smoother2 %<>% filter(rank<=8)


p <- ggplot(gap_smoother3, aes(rank, group = country,
fill = as.factor(country), color = as.factor(country))) +
geom_tile(aes(y = gdpPercap/2,
height = gdpPercap,
width = 0.9), alpha = 0.8, color = NA) +
geom_text(aes(y = 0, label = paste(country, " ")), vjust = 0.2, hjust = 1) +
geom_text(aes(y = gdpPercap,
label = scales::comma(round(gdpPercap))), hjust = 0, nudge_y = 300 ) +
coord_flip(clip = "off", expand = FALSE) +
scale_x_reverse() +
guides(color = FALSE, fill = FALSE) +
labs(title='{closest_state %>% as.numeric %>% floor}',
x = "", y = "GFP per capita") +
theme(plot.title = element_text(hjust = 0, size = 22),
axis.ticks.y = element_blank(), # These relate to the axes post-flip
axis.text.y = element_blank(), # These relate to the axes post-flip
plot.margin = margin(1,1,1,4, "cm")) +
transition_states(year, transition_length = 1, state_length = 0) +
enter_grow() +
exit_shrink() +
ease_aes('linear')

animate(p, fps = 2, duration = 5, width = 600, height = 500)

最佳答案

除了@drf 提供的解决方案之外,您还需要将 scale_y_continuous(scales::comma) 添加到您的 ggplot 命令中。但将它放在 coord_flip 函数之前。

p <- ggplot(gap_smoother3, aes(rank, group = country, 
fill = as.factor(country), color = as.factor(country))) +
geom_tile(aes(y = gdpPercap/2,
height = gdpPercap,
width = 0.9), alpha = 0.8, color = NA) +
geom_text(aes(y = gdpPercap,
label = scales::comma(round(gdpPercap), accuracy=1)),
hjust = 0, nudge_y = 300 ) +
scale_y_continuous(labels = scales::comma) +
... etc.

enter image description here

关于带逗号但没有小数的 R 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61150926/

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