Reputation: 915
I'm wondering how to specify the distance between the first bar of a bar plot with the left-most edge of the x-axis and the last bar with the right-most edge of the x-axis. I've noticed that for some reason, depending on the number of variables being plotted, the distances change to fit them. This is generally fine but doesn't look great for publication purposes.
Here are two plots where the number of variables are identical, however, due to the jittering of the points, one ends up closer to the edge of the x-axis than the other.
Upvotes: 0
Views: 893
Reputation: 15369
If I understand you correctly, then the expand
argument within scale_x_discrete
is what you need. You can read more about it here: http://ggplot2.tidyverse.org/reference/scale_discrete.html:
"a numeric vector of length two giving multiplicative and additive expansion constants. These constants ensure that the data is placed some distance away from the axes."
It is used in format expand = c(MULTIPLICATIVE_VALUE, ADDITIVE_VALUE)
, and an example is provided below:
df <- data.frame(
X = c("v1", "v2", "v3", "v4"),
Y = c(10, 2, 50, 20)
)
# Load Packages
library(ggplot2)
library(gridExtra)
# Build standard plot
plot1 <- ggplot(df, aes(X, Y, fill = X)) +
geom_bar(stat = "identity") +
labs(title = "Standard Plot")
# Add expand argument
plot2 <- plot1 + scale_x_discrete(expand = c(0, 1)) +
labs(title = "Expanded")
# Compare
grid.arrange(plot1, plot2)
Upvotes: 2