I know there are already questions about this, but my case is different and I don't know how to do it.
In my tibble there are a column "values" with a value for each observation, "ind" that divides the observations in two groups of equal size, and "average_time" that contatins the average of the group to which the observation belongs.
This is the code I wrote to get the graph:
my_data %>% ggplot(aes(values, x=ind, fill=ind))
geom_bar(stat="summary", fun=mean)
theme_minimal()
theme(legend.position="none")
Now I want to change the categories at the bottom of each bar from part1 and part2 to "Group 1" and "Group 2", but I can't find a way to do it.
Also, I want to add the average values in the bars. In other words, I want to display the value of each bar in white inside of the bar, something like this:
Can anyone help me with this?
CodePudding user response:
Perhaps this?
library(ggplot2)
my_data %>%
ggplot(aes(ind, values, fill = ind))
geom_bar(stat = "summary", fun = mean)
geom_text(stat = "summary", fun = mean, aes(label = stat(y)),
vjust = 2, size = 12, color = "white")
scale_x_discrete(labels = c("Group 1", "Group 2"), name = "Group")
scale_fill_brewer(palette = "Set1")
theme_minimal(base_size = 20)
theme(legend.position = "none")
Data used
my_data <- data.frame(values = c(100.1, 52.5), ind = c("part1", "part2"))
CodePudding user response:
If you are using the calculation in more than one layer, it might be simpler to precalculate it and feed that into ggplot2:
library(dplyr); library(ggplot2)
mtcars %>%
group_by(gear = as.character(gear)) %>%
summarize(avg_mpg = mean(mpg)) %>%
ggplot(aes(x=gear, y=avg_mpg, fill=gear))
geom_col()
geom_text(aes(label = round(avg_mpg)), vjust = 1.5, color = "white")
scale_x_discrete(labels = c(
"3" = "Group 3",
"4" = "Group 4",
"5" = "Group 5"))
theme_minimal()
theme(legend.position="none")