条形图ggplot,每个条形图对具有不同的背景色

时间:2019-01-29 19:56:37

标签: r ggplot2 bar-chart background-color

有人可以帮我生成一个具有所有显示属性的条形图,并且每对条形图还具有不同的背景颜色吗?
SE是误差线。

Mat <- matrix(c(1.97, 0.61, 0.06, 0.06, 0.61, 0.51, 0.03, 0.25, 2.25, 1.36, 0.15, 0.17, 1.19, 1.41, 0.04, 0.25),ncol=4,byrow=TRUE)

rownames(Mat) <- c("Cognitive Strategies","Motivational Strategies","SE Cognitive Strategies","SE Motivational Strategies")

colnames(Mat) <- c("No Problems","Motivational Problems","Knowledge Problems","Both Problems")

Mat <- as.data.frame(Mat)


barplot(as.matrix(Mat[1:2, 1:4]), main=NULL, ylab = "Number of \n motivational and cognitive Strateiges (CI 95%)", cex.lab = 1.5, cex.main = 1.4, beside=TRUE, col=c("darkblue","red"))

我不知道如何更改每对条的背景色,尤其是如何将其与错误条和图例放在同一代码中。

enter image description here

2 个答案:

答案 0 :(得分:2)

纳丁,
首先ggplot喜欢长格式的数据。您可以按照以下方式转换数据:

library(tidyverse)
library(wrapr)

Mat_long <-
  Mat %>%
  as_tibble() %>%
  mutate(
    Group = c('No Problems','Motivational Problems','Knowledge Problems','Both Problems'),
    xpos = row_number()
  ) %>%
  unite('Cognitive Strategies', c('Cognitive Strategies', 'SE Cognitive Strategies')) %>%
  unite('Motivational Strategies', c('Motivational Strategies', 'SE Motivational Strategies')) %>%
  gather(Type, val, `Motivational Strategies`:`Cognitive Strategies`) %>%
  separate(val, c('val', 'SE'), sep = '_') %>%
  mutate_at(4:5, as.numeric)

Mat_long如下所示:

 A tibble: 8 x 5
  Group                  xpos Type                      val    SE
  <chr>                 <int> <chr>                   <dbl> <dbl>
1 No Problems               1 Motivational Strategies  0.61  0.06
2 Motivational Problems     2 Motivational Strategies  0.51  0.25
3 Knowledge Problems        3 Motivational Strategies  1.36  0.17
4 Both Problems             4 Motivational Strategies  1.41  0.25
5 No Problems               1 Cognitive Strategies     1.97  0.06
6 Motivational Problems     2 Cognitive Strategies     0.61  0.03
7 Knowledge Problems        3 Cognitive Strategies     2.25  0.15
8 Both Problems             4 Cognitive Strategies     1.19  0.04

现在,您可以像这样进行漂亮的绘图:

enter image description here

使用以下代码:

Mat_long %.>%
  ggplot(
    data = .,
    aes(
      x = xpos,
      y = val,
      fill = Type
  )) +
  geom_rect(aes(
      xmin = xpos - .5,
      xmax = xpos + .5,
      ymin = -Inf,
      ymax = Inf,
      fill = Group
    ),
    alpha = .2
  ) +
  geom_col(
    position = position_dodge(.5),
    width = .5
  ) +
  geom_errorbar(aes(
      ymin = val - SE,
      ymax = val + SE
    ),
    position = position_dodge(.5),
    width = .2
  ) +
  geom_text(aes(
      y = val + SE + .1,
      label = val %>% str_replace('\\.', ',')
    ),
    position = position_dodge(.5)
  ) +
  scale_fill_manual(
    values = c(
      '#fb929e',  # Both Problems
      '#235784',  # Cognitive Strategies
      '#ffdfdf',  # Knowledge Problems
      '#fff6f6',  # Motivational Problems
      '#7a5d7e',  # Motivational Strategies
      '#aedefc'   # No Problems
    ),
    breaks = c(
      'Cognitive Strategies',
      'Motivational Strategies'
    )
  ) +
  scale_x_continuous(
    breaks = .$xpos %>% unique(),
    labels = .$Group %>% unique(),
    expand = c(0, 0)
  ) +
  scale_y_continuous(
    labels = function(x) str_replace(x, '\\.', ','),
    limits = c(0, 2.6),
    expand = c(0, 0)
  ) +
  ylab('Number of Motivational and Cognitive Strategies\n(CI 95%)') +
  theme_light() +
  theme(
    legend.position = 'top',
    legend.title = element_blank(),
    legend.spacing.x = unit(1, 'mm'),
    axis.title.x = element_blank()
  )

但是您的问题的答案是...您可以使用geom_rect为每个组设置不同的背景色。问题是geom_rect需要数字值。因此,您必须为每个组添加数字(在我的示例中为xpos),然后再使用scale_x_continous在x轴的更改标签上添加数字。您可以使用Mat_long的{​​{1}}管道传递wrapr数据帧,以便稍后通过调用点%.>%scale_x_continous中使用它:

.

答案 1 :(得分:1)

没有完整的答案,但有一些提示:

要使用ggplot,数据必须为正确的形状(这可能会有所帮助:https://r4ds.had.co.nz/tidy-data.html)。您可以通过tidyverse库中的gather()实现此目标:

library (tidyverse)

plot_df <- gather(Mat, "Strategies", "Number")
plot_df$Problems <- factor(rep(rownames(Mat), 4), levels = rownames(Mat))

我正在对“问题”使用一个因数,以便能够为geom_rect提供xmin和xmax值,该值用于将背景绘制到条形组:

ggplot(plot_df, aes(x = as.numeric(Problems), y = Number, fill = Strategies)) +
  geom_rect(aes(xmin = as.numeric(Problems) - 0.4, xmax = as.numeric(Problems) + 0.4, ymin = 0, ymax = max(Number),  fill = Problems), alpha = 0.2) +
  geom_bar(stat = "identity", position = "dodge2") +
  scale_x_continuous(labels = levels(plot_df$Problems), breaks = seq(1, length(unique(as.character(plot_df$Problems))))) +
  xlab("Problems")

不要看颜色。...有关添加错误栏的信息,请参见https://ggplot2.tidyverse.org/reference/geom_linerange.html