--Hi,
i want to represent a data frame (see attachment) using a bar plot in a facet wrap style grouping by 'Refs'.
I have tried this code:
ggplot(sub, aes(y = as.numeric(EN1),
x = libraries,
group = Refs)) +
geom_bar(stat = "identity", position = "dodge", aes(fill = Refs))
but i have only one column.
thank you --
Your strategy should be to make the data long, so that there is a variable that represents the facet strategy, and a single variable with the y values.
library(tidyverse)
(sub <- expand_grid(libraries=letters[1:2],
Refs=LETTERS[25:26]) |> mutate(EN1 = 1:4,
EN2= 2:5))
# ggplot(sub, aes(y = as.numeric(EN1),
# x = libraries,
# group = Refs)) +
# geom_bar(stat = "identity", position = "dodge", aes(fill = Refs))
(lsub <- pivot_longer(sub,cols = -c(libraries,Refs)))
ggplot(lsub, aes(x=libraries,
y=value,
fill=Refs))+
geom_col(position="dodge") + facet_wrap(~name)
Hi,
yes it is a good solution but negative values are not well plotted, such as:
r - How to label a barplot bar with positive and negative bars with ggplot2 - Stack Overflow
Maybe i need to add some parameters ?
thank you --
Means what exactly? Whats the problem ?
yes, histogram bars in a negative position are not displayed.
I have changed geom_col by geom_bar:
geom_bar(stat = "identity", position = "dodge", aes(fill = Refs)) + facet_wrap(~name)
and now they are displayed.
The default stat for geom_bar is "count", so I understand why in your case you would need to override it to be "identity" , however, that is also the use case for geom_col, whose default stat is "identity".
In other words, geom_col() is a shorter way to write geom_bar(stat="identity") ;
1 Like
ok, i understand now.
Also i try to change the background color of the header facets with:
strip.background = element_rect(fill=factor(lsub$name), colour="black", size=0.5)
but i have only the same color for all the facets. Is it possible to have one different color per header ?
ggplot doesnt support doing that.
Maybe you could do something with ggh4x though.
Facets • ggh4x (teunbrand.github.io)
ok, thank you, i'm going to try this package.