Надин,
прежде всего 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
Теперь вы можете сделать красивый сюжет, подобный этому:
с этим кодом:
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
в моем примере), а затем изменить метки оси X на scale_x_continous
.Вы можете передать Mat_long
фрейм данных с wrapr
'%.>%
pipe, чтобы использовать его позже в scale_x_continous
, вызвав точку .
:
scale_x_continuous(
breaks = .$xpos %>% unique(),
labels = .$Group %>% unique(),
...
)