Передача `top_n` и `range` в ggplot (dplyr) - PullRequest
0 голосов
/ 16 мая 2018

В TidyText Mining Section 3.3 есть прекрасный кусок кода, который я пытаюсь воспроизвести в своем собственном наборе данных.Однако в моих данных я не могу заставить ggplot «запомнить», что я хочу получить данные в порядке убывания и что мне нужно определенное значение top_n.

. Я могу запустить код из TidyText Mining и получаюте же самые графики, которые показывает книга.Однако, когда я запускаю это в своем собственном наборе данных, в обертках фасетов не отображается top_n (кажется, они показывают случайное количество категорий), и данные в каждом фасете не сортируются в порядке убывания.

Я могу воспроизвести эту проблему с некоторыми случайными текстовыми данными и полным кодом - но я также могу повторить проблему с mtcars - что меня действительно смущает.

Я ожидаю, что на следующем графике я покажу миль на галлон в порядке убывания для каждого аспекта, а для каждого аспекта - только верхняя категория 1 .Это не для меня.

require(tidyverse)

mtcars %>%
  arrange (desc(mpg)) %>%
  mutate (gear = factor(gear, levels = rev(unique(gear)))) %>%
  group_by(am) %>%
  top_n(1) %>%
  ungroup %>%
  ggplot (aes (gear, mpg, fill = am)) +
  geom_col (show.legend = FALSE) +
  labs (x = NULL, y = "mpg") +
  facet_wrap(~am, ncol = 2, scales = "free") + 
  coord_flip()

Но я действительно хочу, чтобы диаграмма, подобная этой, была отсортирована, как в книге TidyText (данные только для примера).

require(tidyverse)
require(tidytext)

starwars <- tibble (film = c("ANH", "ESB", "ROJ"),
                  text = c("It is a period of civil war. Rebel spaceships, striking from a hidden base, have won their first victory against the evil Galactic Empire. During the battle, Rebel spies managed to steal secret plans to the Empire's ultimate weapon, the DEATH STAR, an armored space station with enough power to destroy an entire planet. Pursued by the Empire's sinister agents, Princess Leia races home aboard her starship, custodian of the stolen plans that can save her people and restore freedom to the galaxy.....",
                           "It is a dark time for the Rebellion. Although the Death Star has been destroyed, Imperial troops have driven the Rebel forces from their hidden base and pursued them across the galaxy. Evading the dreaded Imperial Starfleet, a group of freedom fighters led by Luke Skywalker has established a new secret base on the remote ice world of Hoth. The evil lord Darth Vader, obsessed with finding young Skywalker, has dispatched thousands of remote probes into the far reaches of space....",
                           "Luke Skywalker has returned to his home planet of Tatooine in an attempt to rescue his friend Han Solo from the clutches of the vile gangster Jabba the Hutt. Little does Luke know that the GALACTIC EMPIRE has secretly begun construction on a new armored space station even more powerful than the first dreaded Death Star. When completed, this ultimate weapon will spell certain doom for the small band of rebels struggling to restore freedom to the galaxy...")) %>%
  unnest_tokens(word, text) %>%
  mutate(film = as.factor(film)) %>%
  count(film, word, sort = TRUE) %>%
  ungroup()

total_wars <- starwars %>%
  group_by(film) %>%
  summarize(total = sum(n))

starwars <- left_join(starwars, total_wars)

starwars <- starwars %>%
  bind_tf_idf(word, film, n)

starwars %>%
  arrange(desc(tf_idf)) %>%
  mutate(word = factor(word, levels = rev(unique(word)))) %>%
  group_by(film) %>%
  top_n(10) %>%
  ungroup %>%
  ggplot(aes(word, tf_idf, fill = film)) +
  geom_col(show.legend = FALSE) +
  labs (x = NULL, y = "tf-idf") +
  facet_wrap(~film, ncol = 2, scales = "free") +
  coord_flip()

1 Ответ

0 голосов
/ 17 мая 2018

Я полагаю, что вас здесь сбивает с толку то, что top_n() по умолчанию использует последнюю переменную в таблице, если вы не укажете ей, какую переменную использовать для упорядочения.В примерах из нашей книги последняя переменная в фрейме данных - это tf_idf, так что именно это используется для упорядочения.В примере mtcars top_n() использует последний столбец в кадре данных для упорядочения;это carb.

Вы всегда можете сказать top_n(), какую переменную вы хотите использовать для упорядочения, передав ее в качестве аргумента.Например, проверьте этот похожий рабочий процесс, используя набор данных diamonds.

library(tidyverse)

diamonds %>%
  arrange(desc(price)) %>%
  group_by(clarity) %>%
  top_n(10, price) %>%
  ungroup %>%
  ggplot(aes(cut, price, fill = clarity)) +
  geom_col(show.legend = FALSE, ) +
  facet_wrap(~clarity, scales = "free") + 
  scale_x_discrete(drop=FALSE) +
  coord_flip()

Создано в 2018-05-17 с помощью представительного пакета (v0.2.0).

Эти примеры наборов данныхне являются идеальными параллелями, потому что они не имеют одной строки на комбинацию характеристик, как это делают фреймы текстовых данных.Я почти уверен, что проблема с top_n() - это проблема.

...