更改geom_bar中的条形颜色

时间:2018-12-17 01:42:26

标签: r ggplot2 geom-bar

我正在尝试使下面代码中的条形颜色从浅蓝色变为深蓝色(从底部到顶部)

q2r <- c("Not good at all", "slightly good",
         "somewhat good", "quite good", "extremely good")

q2 <- survey %>%
  ggplot(aes(x = connect_goals)) +
  geom_bar() +
  scale_x_discrete(limits = q2r) + 
  scale_y_continuous(limits = c(0, 10), breaks = seq(0, 10, 1)) +
  labs(title = "During class, how good is the teacher at connecting 
                the material being taught to clearly stated learning goals?",
       x = "", y = "") +
  coord_flip()

Picture of visualization

2 个答案:

答案 0 :(得分:3)

第一个问题的好开始!下次,请记住包含您的数据样本,为我们提供可重复的示例以帮助您。

要正确执行此操作,您只需要适当地分解数据,设置填充的美观映射,然后应用缩放功能来正确设置颜色即可。

library(tidyverse)

#Reproducible data for your example
survey <- tibble(connect_goals = c("Not good at all","slightly good","slightly good","somewhat good",
                                   "somewhat good","somewhat good","somewhat good","somewhat good", "extremely good","extremely good",
                                   "extremely good","extremely good","extremely good"))

q2r <- c("Not good at all", "slightly good",
         "somewhat good", "quite good", "extremely good")

# Create a factor out of connect goals, which sets the proper order for scales.
survey %>%
  mutate(connect_goals = factor(connect_goals, q2r)) %>% 
  ggplot(aes(x = connect_goals, fill = connect_goals)) +
  geom_bar() +
  scale_x_discrete(limits = q2r) + 
  scale_fill_brewer(direction = -1, palette = "Blues") +
  scale_y_continuous(limits = c(0, 10),
                     breaks = seq(0, 10, 1)) +
  labs(title = "During class, how good is the teacher at connecting 
                the material being taught to clearly stated learning goals?",
       x = "", y = "") +
  coord_flip()

reprex package(v0.2.1)于2018-12-16创建

答案 1 :(得分:1)

这里没有您的数据是一个建议的解决方案。您应该设置自己的审美观。另外,还有多种方法可以手动更改颜色。例如,您可以键入?scale_fill_manual()并查看其工作方式。如果记忆正确,您可能正在寻找?scale_fill_discrete()和Blues Set。感谢Jake的评论,我将编辑此答案。

q2r <- c("Not good at all", "slightly good",
    "somewhat good", "quite good", "extremely good")

  q2 <- survey %>%
        ggplot(aes(x = connect_goals,fill=connect_goals)) +
        geom_bar() +
        scale_x_discrete(limits = q2r) + 
        scale_y_continuous(limits = c(0, 10),
             breaks = seq(0, 10, 1)) +
        labs(title = "During class, how good is the teacher at connecting 
            the material being taught to clearly stated learning goals?",
             x = "", y = "") +
         coord_flip()

干杯!