We are working with a data frame that looks like this
df <- data.frame(
n = c(0, 0, 0, 5, 5, 5, 100, 100, 100),
y = c(1, 2, 1.5, NA, 2, 2.5, NA, 3, 4.5),
f = c("i", "j", "k", "i", "j", "k", "i", "j", "k")
)
To create a bar plot, I wrote this code
colors <- c("i" = "#1F1F1F", "j" = "#606060", "k" = "#B3B3B3")
ggplot(data = df, aes(x = n, y = y, fill = f), show.legend = TRUE) +
geom_bar(stat = "identity", position = "dodge", width = 3.5) +
scale_fill_manual(values = colors, labels = c("i", "j", "k"), labs(title = "Title")) +
theme_bw()
It works fine but there's one problem in the position of ticks on the x-axis.
How can we have three breaks labeled 0
, 5
, and 100
but with equal distances from each other?
I tried this scale_x_continuous(expand = c(0.02, 0.02), breaks=?, labels=c("0", "5", "100"))
but I'm not sure how to define breaks
Given your toy data df
mimics the real data, coercing n
to factor might a sufficient solution. To accomplish that, all we need to change is x = n
to x = as.factor(n)
.
library(ggplot2)
df <- data.frame(
n = c(0, 0, 0, 5, 5, 5, 100, 100, 100),
y = c(1, 2, 1.5, NA, 2, 2.5, NA, 3, 4.5),
f = c("i", "j", "k", "i", "j", "k", "i", "j", "k")
)
colors <- c("i" = "#1F1F1F", "j" = "#606060", "k" = "#B3B3B3")
ggplot(data = df, aes(x = as.factor(n), y = y, fill = f), show.legend = TRUE) +
geom_bar(stat = "identity", position = "dodge") +
scale_fill_manual(values = colors, labels = c("i", "j", "k"), labs(title = "Title")) +
labs(x = "n") +
theme_bw()
#> Warning: Removed 2 rows containing missing values (`geom_bar()`).
Created on 2023-11-22 with reprex v2.0.2