Метка R с запятыми, но без десятичных знаков - PullRequest
0 голосов
/ 11 апреля 2020

Моя цель - создавать ярлыки с запятыми, но без десятичных знаков. Допустим, у меня есть ggplot со следующим разделом:

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

Это почти то, что мне нужно. Это дает мне запятые, но имеет десятичную дробь. Я видел здесь ( метки оси с запятой, но без десятичных знаков ggplot ), что comma_format() может быть хорошим, но я думаю, что метка в моем случае нуждается в аргументе данных, который comma_format() не принимает. Что я могу сделать?

Обновление:

В качестве примера того, когда возникает эта проблема, смотрите следующее, которое использует gganimate и имеет гораздо больше возможностей. Код, полученный из ответа Джона Спринга на Анимированная гистограмма с пересекающимися столбцами

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)

1 Ответ

2 голосов
/ 11 апреля 2020

В дополнение к решению, предоставленному @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

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...