I have several geom_bar ggplots where I have long names for x-axis text. If I plot them at angle=90, it takes a lot of room at the bottom of the graph, so I am trying angle=45. This causes the left hand side of the first label to be cut off. Is there a way to increase the left margin?
(not allowed to post an image example)
ggplot(aes(x = cm, y = ahead_aadt),
data = sbt) +
geom_point( ) + geom_line() +
ggtitle("Ahead AADT Traffic Counts On US 101 in S Santa Barbara Cty") +
theme(axis.text.x = element_text(angle=45, size = 9,
color = "black", face = "plain", vjust = 1, hjust = 1),
panel.grid.major.x = element_line(colour = "black", linetype = "dotted")) +
xlab("Cumulative Mileage") + ylab("Ahead AADT") +
scale_x_continuous(breaks = sbt$cm,
labels = sbt$description)
We can rotate axis text labels using theme() function in ggplot2. To rotate x-axis text labels, we use “axis. text. x” as argument to theme() function.
Rotate axis text labels. For example, for a vertical x axis text label you can specify the argument angle as follow: p + theme(axis. text. x = element_text(angle = 90)) .
Use scale_xx() functions It is also possible to use the functions scale_x_continuous() and scale_y_continuous() to change x and y axis limits, respectively.
Changing axis labels To alter the labels on the axis, add the code +labs(y= "y axis name", x = "x axis name") to your line of basic ggplot code. Note: You can also use +labs(title = "Title") which is equivalent to ggtitle .
There would be a better solution to your problem: Just follow the link user3055034 provided. Tweak plot.margin
with the new margin()
in analogy to my example below.
library(ggplot2)
# long labels
labels <- c(paste(c(letters, letters), collapse = ""), "6", "8")
ggplot(mtcars, aes(as.factor(cyl), mpg)) +
geom_point() +
scale_x_discrete(labels = labels) +
theme(axis.text.x = element_text(angle = 45, size = 9,
color = "black", face = "plain", vjust = 1, hjust = 1),
plot.margin = margin(10, 10, 10, 100))
This is probably not the best answer, but I added several "\n\n\n" before my y-axis label text which made the label text wider. This moves the actual plot and its associated labels farther to the right, giving more room for the text on the left.
ggplot(aes(x = cm, y = ahead_aadt),
data = sbt) +
geom_point( ) + geom_line() +
ggtitle("Ahead AADT Traffic Counts On US 101 in S Santa Barbara Cty") +
theme(axis.text.x = element_text(angle=45, size = 9,
color = "black", face = "plain", vjust = 1, hjust = 1),
panel.grid.major.x = element_line(colour = "black", linetype = "dotted")) +
xlab("Cumulative Mileage") + ylab("\n\n\nAhead AADT") +
scale_x_continuous(breaks = sbt$cm,
labels = sbt$description)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With