geom_bar position width issue in ggplot2
为了一种有趣的学习方式
鲍勃罗斯画作上的条形图。我附上了
我在下面尝试的代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | 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 |
1 2 3 4 | ross_tidy2 %>% ggplot(data = ., aes(x = reorder(tag, perc), y = perc)) + geom_bar(stat ="identity",width = 0.9) + coord_flip() |
就够了
你不需要 position_dodge (你没有几个组)
条形宽度太大,它们很难"躲避"对方。我将宽度设置为 1 并没有收到错误。