I have a data frame df with two-factor variables. I used ggplot2
to make a barplot:
library(ggplot2)
df <- data.frame(x = factor(c("2", "1", "1", "5", "3", "2", "4", "1", "5", "3")),
group = factor(c("one", "two", "two", "two", "one", "two", "one",
"one", "two", "two"))
)
ggplot(df, aes(x = x))
geom_bar(aes(fill = group))
I want to make the exact same barplot using the ggbarplot
function from the ggpubr
package, but arguments for both x and y are required.
library(ggpubr)
ggbarplot(df,
x = "x", y = "", fill = "group", color = "group")
How can I get count of x on the y axis as I was able to do using ggplot2?
I imagine this is relatively simple but I just can't figure it out - thanks!
CodePudding user response:
Unfortunately, this is not possible without creating a column with the count. What you can do is use count
from dplyr
like this:
library(ggplot2)
df <- data.frame(x = factor(c("2", "1", "1", "5", "3", "2", "4", "1", "5", "3")),
group = factor(c("one", "two", "two", "two", "one", "two", "one",
"one", "two", "two"))
)
ggplot(df, aes(x = x))
geom_bar(aes(fill = group))
library(ggpubr)
library(dplyr)
df %>%
count(group, x) %>%
ggbarplot(.,
x = "x",
y = "n",
fill = "group",
color = "group",
xlab = "count")
Created on 2022-08-26 with reprex v2.0.2
As you can see, it has the same result.
CodePudding user response:
To remove legend:
library(ggpubr)
library(dplyr)
df %>%
count(group, x) %>%
ggbarplot(.,
x = "x",
y = "n",
fill = "group",
color = "group",
xlab = "count")
theme(legend.position = "none")