Rotating and Spacing Axis Labels in Ggplot2

Rotating and spacing axis labels in ggplot2

Change the last line to

q + theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))

By default, the axes are aligned at the center of the text, even when rotated. When you rotate +/- 90 degrees, you usually want it to be aligned at the edge instead:

alt text

The image above is from this blog post.

Rotating x label text in ggplot

You need to change the order of the layers, otherwise theme_bw will override theme:

ggplot(res, aes(x=TOPIC,y=count), labs(x=NULL)) + 
scale_y_continuous(limits=c(0,130),expand=c(0,0)) +
scale_x_discrete("",labels=c("ANA"="Anatomy","BEH"="Behavior","BOUND"="Boundaries",
"CC"="Climate change","DIS"="Disease","EVO"="Evolution",
"POPSTAT"="Pop status","POPABU"="Pop abundance",
"POPTR"="Pop trend","HARV"="Harvest","HAB"="Habitat",
"HABP"="Habitat protection","POLL"="Pollution",
"ZOO"="Captivity","SHIP"="Shipping","TOUR"="Tourism",
"REPEC"="Reprod ecology","PHYS"="Physiology","TEK"="TEK",
"HWC"="HWC","PRED"="Predator-prey","METH"="Methods",
"POPGEN"="Pop genetics","RESIMP"="Research impact",
"ISSUE"="Other","PROT"="Protection","PA"="Protected areas",
"PEFF"="Protection efficiency","MINOR"="Minor")) +
theme_bw(base_size = 16) +
theme(axis.text.x=element_text(angle=90,hjust=1)) +
geom_bar(stat='identity') +
ggtitle("Peer-reviewed papers per topic")

Rotate axis TEXT labels in R

Very possible to do what you're looking to do. The axis title is different than the text (the labels of the tick marks on the axis). Consequently, the theme() element you want to address is axis.title.y. As with the axis text, you address using element_text() and supply an angle. In this case, the angle is set to 90 degrees by default, so you want to rotate back to angle=0. Importantly, you will want to adjust the vertical alignment too, which is set to be aligned at the top by default. To put the title in the middle of the axis, you need a vertical alignment of 0.5.

p <- your plot code
p + theme(axis.title.y=element_text(angle=0, vjust=0.5))

Sample Image

X axis labels cut off in ggplot when rotating

I don't see any way to do this automatically natively using ggplot2 tools, so why not write a small function that sets the size of the margin based on the number of characters in the leftmost x category value?

margin_spacer <- function(x) {
# where x is the column in your dataset
left_length <- nchar(levels(factor(x)))[1]
if (left_length > 8) {
return((left_length - 8) * 4)
}
else
return(0)
}

The function can deal with a character column (or factor), and checks the number of characters in the first level (which would appear on the left in the plot). Fiddling around, it seemed anything longer than 8 posed an issue for the plot code, so this adds 4 points to the margin for every character past 8 characters.

Note also, that I changed the angle of the x axis text on your plot - I think 22.5 is a bit too shallow and you get a lot of overlapping with the size of your text on my graphics device. This means that 8 and 4 value may not work quite as well for you, but here's how it works for a few different data frames.

Here's the new plot code:

ggplot(data = d, aes(x = category, y = n, fill = category)) +
geom_bar(stat = "identity") +
facet_grid(rows = vars(year), cols = vars(type)) +
theme(
axis.text.x = element_text(angle = 40, hjust = 1, size = 12),
plot.margin = margin(l = 0 + margin_spacer(d$category))
)

I created the following plots by changing the code where d$categories is defined. I am showing you the output using the code above where the first entry in categories <- c(...) is changed accordingly for each one. You'll note it works pretty well unless it's crazy long. As the text gets really long, the text size may have to be adjusted as well. If you think your users are going to get crazy with labels, you can use a similar strategy to adjust text size... but that's probably overkill.

"Enter" (5 characters)

Sample Image

"Entertain" (9 characters)

Sample Image

"Entertainer" (11 characters)

Sample Image

"Entertainment" (13 characters)

Sample Image

"Quality Entertainment" (21 characters)

Sample Image

Can I create axis labels with vertical-reading text with ggplot?

Using str_replace_all:

str_vert <- function(x) str_replace_all(x, paste0("(.{1})"), "\\1\n")

example:

library(tidyverse)
data <- tibble(name = c("AAA", "BBB"), value = c(0.3, 0.2))
str_vert <- function(x) str_replace_all(x, paste0("(.{1})"), "\\1\n")

ggplot(data, aes(name, value)) +
geom_col() +
scale_x_discrete(label = str_vert)

Sample Image

How to rotate the axis labels in ggplot2?

For the rotation angle of the axis text you need to use element_text(). See this post on SO for some examples. For spacing over two lines I would add a "\n" on the location in the string where you want to put the newline.

This will set the correct orientation for the y axis text and force a line break:

finalPlot + ylab("Number of\nSolutions") + 
theme(axis.title.y = element_text(angle = 0))

preserving axes label text when labels are rotated in `ggplot2`

Try this:

# setup
set.seed(123)
library(ggplot2)

# plot
(p <-
ggplot(mtcars, aes(as.factor(am), wt)) + geom_point() +
scale_x_discrete(labels = c("0\n(n = 19)", "1\n(n = 13)"))+
theme(axis.text.x = element_text(angle=90)))

Sample Image



Related Topics



Leave a reply



Submit