Reputation: 345
I have a graph in Excel that I'd like to replicate in R if it's even possible. I am new to R, so any guidance will be appreciated. So my data looks like this
I can include the file if anyone wants it.
I'd like to plot the same graph as in the Excel file but using R. So, is there a way to have a kind of subset for the x-axis values that belong to the main value?
I looked through the ggplot documentation and How to plot side-by-side with sub labels and without space between subplots, but to no avail.
Upvotes: 1
Views: 1754
Reputation: 61154
This can be helpful
library(tidyr)
library(ggplot2)
df %>%
pivot_longer(ACI:SB) %>%
mutate(across(where(is.character), as.factor)) %>%
ggplot(aes(x = R, y = value, fill=name))+
geom_bar(stat="identity", position = "dodge", width=0.75)+
facet_wrap(~A, nrow=1, strip.position="bottom") +
theme(legend.position = "bottom") +
labs(fill="", y="", x="")
Produces:
If you want "to speak R with Excel accent" and convert this nice plot into a default excel plot, then you can add at the end of the plot theme_excel_new()
from ggtheme package
library(ggthemes)
... +
theme_excel_new()
It'll give the following plot
Sample data:
structure(list(A = c(25, 25, 25, 50, 50, 50, 100, 100, 100, 250,
250, 250), R = c("R1", "R2", "R3", "R1", "R2", "R3", "R1", "R2",
"R3", "R1", "R2", "R3"), ACI = c(2.94, 1.91, 8.86, 5.03, 8.77,
1.89, 7.58, 7.24, 9.44, 5.48, 7.12, 3.89), PB = c(1.01, 9.27,
2.83, 5.91, 1.1, 8.41, 3.18, 7.83, 2.68, 2.19, 5.17, 2.69), NB = c(1.81,
5.19, 5.63, 1.29, 2.56, 7.18, 9.61, 1, 7.63, 9.48, 8.19, 3.08
), Bca = c(6.5, 9.53, 9.54, 3.4, 2.62, 1.65, 3.22, 5.1, 9.24,
5.11, 2.58, 0.46), SB = c(4.18, 8.54, 3.47, 1.31, 3.74, 6.31,
3.9, 6.9, 6.89, 5.55, 4.3, 4.53), `round(2)` = c(2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2)), class = "data.frame", row.names = c(NA,
-12L))
Upvotes: 1
Reputation: 2321
You can use either geom_bar(position = "dodge")
or facet_wrap()
to achieve your desired results. Please note that you'll need to name all your variables before plotting as it looks like the first two columns of your dataframe do not have names.
library(tidyverse)
data(mtcars)
# make a nested dataframe for example purposes
df <- mtcars %>%
rownames_to_column(var = "rowname") %>%
select(c(1:5)) %>%
pivot_longer(cols = -c(rowname)) %>%
head(n = 20)
ggplot(df, aes(x = name, y = value, fill = name)) +
geom_bar(stat = "identity") +
facet_wrap(~rowname, nrow = 1) # use facet_wrap to display nestedness
ggplot(df, aes(x = rowname, y = value, fill = name)) +
geom_bar(position = "dodge", stat = "identity")
Upvotes: 2