ggplot2中的geom_bar位置宽度问题

时间:2018-07-14 17:24:01

标签: r ggplot2

以一种有趣的方式学习ggplot2,我正在尝试重现第五十八 barplot on bob ross paintings。我已经附上了 我在下面的尝试代码:

library(tidyverse)
library(ggthemes)

# OPTION 1 - Download raw data directly from source
ross_url <- "https://raw.githubusercontent.com/fivethirtyeight/data/master/bob-ross/elements-by-episode.csv"
ross_dat <- read_csv(file = ross_url)

ross_tidy <- ross_dat %>%
                gather(key = tag, value = indicator, APPLE_FRAME:WOOD_FRAMED)
new_tag_fmt <- function(str){
    str_replace_all(string = str, pattern = "_",
                             replacement = " ") %>%
        str_trim() %>%
        str_to_title() %>%
        return()
}

tot_episodes <- ross_tidy %>% select(EPISODE) %>% n_distinct()
ross_tidy2 <- ross_tidy %>%
                group_by(tag) %>%
                summarize(total = sum(indicator)) %>%
                ungroup() %>%
                mutate(tag = as.factor(new_tag_fmt(str = tag)),
                              perc = round(total/tot_episodes, 2),
                              perc_fmt = scales::percent(perc)) %>%
                arrange(desc(total)) %>%
                filter(total >= 5)


ggplot(ross_tidy2, aes(x = reorder(tag, perc), y = perc)) +
    geom_bar(stat = "identity", fill = "#198DD1",
                      width = 2, position = "dodge") +
    coord_flip() +
    labs(title = "The Paintings of Bob Ross",
                  subtitle = "Percentage containing each element") +
    geom_text(data = ross_tidy2, nudge_y = 0.02, angle = 270,
                           aes(reorder(tag, total), y = perc, label = perc_fmt),
                       family = "Courier", color = "#3E3E3E") +
    scale_color_fivethirtyeight("cyl") +
    theme_fivethirtyeight() +
    theme(panel.border = element_blank(),
                   panel.grid.major = element_blank(),
                   panel.grid.minor = element_blank(),
                   axis.line = element_blank(),
                   axis.ticks.x = element_blank(),
                   axis.text.x = element_blank(),
                   plot.title = element_text(size = 18, hjust=-0.5),
                   plot.subtitle = element_text(size = 14, hjust=-0.5),
                   axis.text.y = element_text(size = 12))
#> Warning: position_dodge requires non-overlapping x intervals

reprex package(v0.2.0)于2018-07-14创建。

这里的问题是我不断收到警告:

  

警告:position_dodge需要x间隔不重叠

任何人都可以在代码tag变量中向我展示此问题吗 是一个因素,即是绝对的,所以我认为上述方法应该有效。

注意:完全归功于Fivethirtyeight,因为他们提供了数据来再现他们的作品!

2 个答案:

答案 0 :(得分:1)

ross_tidy2 %>%
 ggplot(data = ., aes(x = reorder(tag, perc), y = perc)) +
  geom_bar(stat = "identity",width = 0.9) +
  coord_flip() 

足够了
您不需要position_dodge(您没有几个组)

enter image description here

答案 1 :(得分:0)

栏的宽度太大,因此很难彼此“躲避”。我将宽度设置为1,但没有收到错误。