Можно ли сделать этот тип графика с помощью ggplot2? - PullRequest
0 голосов
/ 30 августа 2018

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

Можно ли это сделать с ggplot2? А как насчет текста под решеткой? Я думаю, что они должны быть жестко закодированы в кодах ggplot2. И как вы выравниваете этот текст?

Bar graph

Ответы [ 3 ]

0 голосов
/ 30 августа 2018

Это довольно близко:

# Generate sample data (I'm too lazy to type out the full labels)
df <- data.frame(
    perc = c(60, 36, 44, 41, 42, 57, 34, 52),
    type = rep(c("blue", "green"), 4),
    label = rep(c(
        "Individual reports created as needed",
        "Regular reports on single topics",
        "Analytics using data integrated from multiple systems",
        "Business unit-specific dashboards and visuals"), each = 2))


library(ggplot2)
ggplot(df, aes(1, perc, fill = type)) +
    geom_col(position = "dodge2") +
    scale_fill_manual(values = c("turquoise4", "forestgreen"), guide = FALSE) +
    facet_wrap(~ label, ncol = 1, strip.position = "bottom") +
    geom_text(
        aes(y = 1, label = sprintf("%i%%", perc)),
        colour = "white",
        position = position_dodge(width = .9),
        hjust = 0,
        fontface = "bold") +
    coord_flip(expand = F) +
    theme_minimal() +
    theme(
        axis.title = element_blank(),
        axis.text = element_blank(),
        axis.ticks = element_blank(),
        panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(),
        strip.text = element_text(angle = 0, hjust = 0, face = "bold"))

enter image description here

Несколько объяснений:

  1. Мы используем уклоненные столбцы и соответствующие уклоненные метки с position = "dodge2" (обратите внимание, что для этого требуется ggplot_ggplot2_3.0.0, в противном случае используйте position = position_dodge(width = 1.0)) и position = position_dodge(width = 0.9) соответственно.
  2. Мы используем facet_wrap и форсируем макет из одной колонки; полосовые надписи перемещаются вниз.
  3. Мы вращаем весь график с помощью coord_flip(expand = F), где expand = F гарантирует, что выровненные по левому краю (hjust = 0) тексты фасетных полос выровнены с 0.
  4. Наконец, мы настраиваем тему, чтобы увеличить общее эстетическое сходство.
0 голосов
/ 30 августа 2018

Вы можете попробовать использовать данные из другого ответа. Различия: мы используем scales::percent для рисования процентов. Мы используем ggpubr::theme_transparent() тему, чтобы настроить как можно меньше.

df$perc <- c(.60, .36, .44, .41, .42, .57, .34, .52)

ggplot(df, aes(label, perc, label=scales::percent(round(perc,2)),fill= factor(type))) + 
   geom_col(position = position_dodge(0.9), show.legend = F) + 
   geom_text(aes(y=0), position = position_dodge(0.9), size=5, hjust=-0.1, color="white", fontface="bold") +
   scale_y_continuous("",labels = scales::percent) + 
   coord_flip(expand = F) + 
   facet_wrap(~label,scales = "free", strip.position = "bottom", ncol = 1) +
   ggpubr::theme_transparent() +
   xlab("") + 
   theme(strip.background = element_blank(),
         strip.text = element_text(size = 12, face = "bold",hjust=0))

enter image description here

0 голосов
/ 30 августа 2018

Может быть, использовать фасет и корректировать стиль?

dat <- data.frame(perc = c(60, 20, 90, 30), col = rep(c("gr1", "gr2"), 2),
                  text = c(rep("text1", 2), rep("text2", 2)))

ggplot(dat, aes(y = perc, x = col, fill = col)) +
  geom_bar(stat = "identity", position = "dodge") +
  coord_flip() +
  facet_wrap(~text, strip.position = "bottom", ncol = 1)
...