In the following ggplot in r, I would like my “n” labels to be aligned with the left side of each bar — as they are on the pink bars but not on the blue bars. Somehow, the dodging is not transferring to the n label for the right-hand blue bars.
I’ve looked at Position geom_text on dodged barplot which suggests using dodge(0.9). This has not helped in my case. This answer: Add text on top of a faceted dodged bar chart led me to add the “group = ” in my ggplot code. This didn’t help.
All help would be appreciated and please let me know if I can add any clarification here!
Here’s a minimal reproducible example:
<code>factor <- c("Included", "Included", "Excluded", "Excluded")
affected <- c("Affected", "Not Affected", "Affected", "Not Affected")
mean_rating <- c(76.00000, 39.55556, 49.00000, 41.62069)
n <- c(23, 2, 17, 19)
df1 <- data.frame(factor, affected, mean_rating, n)
ggplot(df1, aes(x = factor, y = mean_rating, fill = affected, group = affected)) +
geom_bar(stat = "identity", position = position_dodge(0.9)) +
geom_text(aes(label = paste("n =", n), y = mean_rating),
hjust = 1, vjust=-0.35, position = position_dodge(0.9)) +
guides(fill = FALSE, color = FALSE)
</code>
<code>factor <- c("Included", "Included", "Excluded", "Excluded")
affected <- c("Affected", "Not Affected", "Affected", "Not Affected")
mean_rating <- c(76.00000, 39.55556, 49.00000, 41.62069)
n <- c(23, 2, 17, 19)
df1 <- data.frame(factor, affected, mean_rating, n)
ggplot(df1, aes(x = factor, y = mean_rating, fill = affected, group = affected)) +
geom_bar(stat = "identity", position = position_dodge(0.9)) +
geom_text(aes(label = paste("n =", n), y = mean_rating),
hjust = 1, vjust=-0.35, position = position_dodge(0.9)) +
guides(fill = FALSE, color = FALSE)
</code>
factor <- c("Included", "Included", "Excluded", "Excluded")
affected <- c("Affected", "Not Affected", "Affected", "Not Affected")
mean_rating <- c(76.00000, 39.55556, 49.00000, 41.62069)
n <- c(23, 2, 17, 19)
df1 <- data.frame(factor, affected, mean_rating, n)
ggplot(df1, aes(x = factor, y = mean_rating, fill = affected, group = affected)) +
geom_bar(stat = "identity", position = position_dodge(0.9)) +
geom_text(aes(label = paste("n =", n), y = mean_rating),
hjust = 1, vjust=-0.35, position = position_dodge(0.9)) +
guides(fill = FALSE, color = FALSE)