ggplot中的嵌套帕累托图

时间:2019-07-29 16:09:30

标签: r ggplot2

matryoshka pareto plot

我经常生成pareto图表,使我想起俄罗斯套娃(俄罗斯套娃)。

  1. [Top Graph]-我将以蓝色突出显示的第一个pareto的第一栏。这是最大的“按制造商计数” ,恰好是道奇汽车。
  2. [中间图]-这是上面第一个突出显示的条的爆炸图。所有栏都以蓝色突出显示以表示这一事实。
  3. [底部图形]-这是中间图形中第一个突出显示的条的爆炸图。所有栏都以蓝色突出显示,并以红色突出显示以表示这一事实。

如果我可以批评自己的作品,这在视觉上并不令人愉悦,更重要的是,在直观上也不容易理解。

我用Rggplot2标签获得的solutins往往光彩夺目(我认为)。有更好的方法。你有吗?

library(tidyverse)
library(cowplot)

p1 <- mpg %>% 
  count(manufacturer) %>% 
  top_n(5) %>% 
  ggplot(aes(reorder(manufacturer, -n), n)) + 
  geom_col() + 
  geom_col(data = mpg %>% count(manufacturer) %>% top_n(1), fill = "blue") + 
  labs(x = NULL, y = NULL, title = "Count by Manufacturer")

p2 <- mpg %>% 
  filter(manufacturer == "dodge") %>% 
  count(cyl) %>% 
  ggplot(aes(reorder(cyl, -n), n)) + 
  geom_col(fill = "blue") + 
  geom_col(data = mpg %>% 
             filter(manufacturer == "dodge", cyl == 8) %>% 
             count(cyl),
           fill = "blue",
           color = "red",
           size = 2) + 
  labs(x = NULL, y = NULL, title = "Dodge cylinder count")

p3 <- mpg %>% 
  filter(manufacturer == "dodge", cyl == 8) %>% 
  count(cty) %>% 
  mutate(cyt = as.character(cty)) %>% 
  ggplot(aes(reorder(cty, -n), n)) + 
  geom_col(fill = "blue", color = "red", size = 2) + 
  labs(x = NULL, y = NULL, title = "Dodge V8 cty mpg count")

plot_grid(p1, p2, p3, ncol = 1)

1 个答案:

答案 0 :(得分:1)

涉及一点点麻烦,但是您可以在highcharter中使用追溯。 这将使您具有交互性。

library(tidyverse)
library(highcharter)
library(purrr)

# DATA for the 3 plots
d1 <- mpg %>% 
  count(manufacturer) %>% 
  top_n(5) %>%
  arrange(desc(n)) %>%
  mutate(drilldown = manufacturer)

d2 <- mpg %>% 
  filter(manufacturer == "dodge") %>% 
  count(cyl) %>% 
  mutate(cyl = as.character(cyl),
         # Required for the second drilldown
         drilldown = as.character(cyl),
         name = as.character(cyl), 
         y = n) %>% 
  arrange(desc(n))

d3 <- mpg %>% 
  filter(manufacturer == "dodge", cyl == 8) %>% 
  count(cty) %>% 
  mutate(cty = as.character(cty),
         cyt = as.character(cty)) %>%
  arrange(desc(n))

hc <- highchart() %>%
  hc_add_series(type = "column", data = d1, hcaes(y = n, x = manufacturer)) %>%
  hc_xAxis(type = "category")


hc2 <- hc %>%
  hc_drilldown(
    allowPointDrilldown = TRUE,
    series = list(
      list(id = "dodge", 
           data = purrr::transpose(d2),
           type = "column"),
      list(id = "8",
           data = list_parse2(d3),
      type = "column")))

hc2