I have a question concerning the fill field in geom_bar
of the ggplot2 package.
I would like to fill my geom_bar with a variable (in the next example the variable is called var_fill
) but order the geom_plot
with another variable (called clarity
in the example).
How can I do that?
Thank you very much!
The example:
rm(list=ls())
set.seed(1)
library(dplyr)
data_ex <- diamonds %>%
group_by(cut, clarity) %>%
summarise(count = n()) %>%
ungroup() %>%
mutate(var_fill= LETTERS[sample.int(3, 40, replace = TRUE)])
head(data_ex)
# A tibble: 6 x 4
cut clarity count var_fill
<ord> <ord> <int> <chr>
1 Fair I1 210 A
2 Fair SI2 466 B
3 Fair SI1 408 B
4 Fair VS2 261 C
5 Fair VS1 170 A
6 Fair VVS2 69 C
I would like this order of the boxes [clarity] :
library(ggplot2)
ggplot(data_ex) +
geom_bar(aes(x = cut, y = count, fill=clarity),stat = "identity", position = "fill", color="black")
with this fill (color) of the boxes [var_fill] :
ggplot(data_ex) +
geom_bar(aes(x = cut, y = count, fill=var_fill),stat = "identity", position = "fill", color="black")
EDIT1 : answer found by missuse :
p1 <- ggplot(data_ex) + geom_bar(aes(x = cut, y = count, group = clarity, fill = var_fill), stat = "identity", position = "fill", color="black")+ ggtitle("var fill")
p2 <- ggplot(data_ex) + geom_bar(aes(x = cut, y = count, fill = clarity), stat = "identity", position = "fill", color = "black")+ ggtitle("clarity")
library(cowplot)
cowplot::plot_grid(p1, p2)
EDIT2 : Now i tried to do this with ggmosaic extension with the help of missuse
rm(list=ls())
set.seed(1)
library(ggplot2)
library(dplyr)
library(ggmosaic)
data_ex <- diamonds %>%
group_by(cut, clarity) %>%
summarise(count = n()) %>%
ungroup() %>%
mutate(residu= runif(nrow(.), min=-4.5, max=5)) %>%
mutate(residu_classe = case_when(residu < -4~"< -4 (p<0.001)",(residu >= -4 & residu < -2)~"[-4;-2[ (p<0.05)",(residu >= -2 & residu < 2)~"[-2;2[ non significatif",(residu >= 2 & residu < 4)~"[2;4[ (p<0.05)",residu >= 4~">= 4 (p<0.001)")) %>%
mutate(residu_color = case_when(residu < -4~"#D04864",(residu >= -4 & residu < -2)~"#E495A5",(residu >= -2 & residu < 2)~"#CCCCCC",(residu >= 2 & residu < 4)~"#9DA8E2",residu >= 4~"#4A6FE3"))
ggplot(data_ex) +
geom_mosaic(aes(weight= count, x=product(clarity, cut)), fill = data_ex$residu_color, na.rm=T)+
scale_y_productlist() +
theme_classic() +
theme(axis.ticks=element_blank(), axis.line=element_blank())+
labs(x = "cut",y="clarity")
But I would like to add this legend (below) on the right of the plot but I don't know how I could do it because the fill field is outside aes so scale_fill_manual does not work...