首页 > 解决方案 > 更改 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()

可视化图片

标签: rggplot2geom-bar

解决方案


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

要正确执行此操作,您只需正确考虑数据,设置填充的美学映射,然后应用缩放功能以正确设置颜色。

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 包(v0.2.1)于 2018 年 12 月 16 日创建


推荐阅读