简体   繁体   中英

Adjust plot axis labels to fit in .pdf

I'd like to save a histogram as .pdf but when I do it not all x-axis labels are visible. Is it there a way to automatically adjust the size of the plot so that all labels fit nicely and can be read? Thanks a lot in advance for your help!!

# Example data
dd <- iris
dd$Species <- as.character(dd$Species)
dd$Species[dd$Species=="setosa"] <- "setosa and more text that should also fit in the pdf"
dd$Species[dd$Species=="versicolor"] <- "versicolor and more text that should also fit in the pdf"
dd$Species[dd$Species=="virginica"] <- "virginica and more text that should also fit in the pdf"
dd$Species <- as.factor(dd$Species)

# Plotting & saving as .pdf
windows()
plot(dd$Species)
dev.copy(pdf, file="%/test.pdf") # % is the directory in my computer
dev.off()

If the problem is you need give more information on each label with more text, you can use next line

dd <- iris
dd$Species <- as.character(dd$Species)
dd$Species[dd$Species=="setosa"] <- "setosa is the name \n of iris-more text"
dd$Species[dd$Species=="versicolor"] <- "versicolor is the name \n of iris-more text "
dd$Species[dd$Species=="virginica"] <- "virginica is the name \n of iris-more text"
dd$Species <- as.factor(dd$Species)
plot(dd$Species)

在此处输入图片说明

When you print to pdf, what matters is the size of the pdf rather than the plot, for the labels to fit. In other words if you use

pdf("filename.pdf", width = W)
plot(dd$Species)
dev.off()

and the width parameter W is large enough, you should get a pdf in which the bars are wide enough so that all labels are visible.

This, however, may not be aesthetically pleasing, in which case you may want to try using ggplot2. This will enable you to play around with the labels more easily. For example, you can rotate all labels by an angle so that they all fit nicely

library(ggplot2)
ggplot(dd, aes(Species)) + 
    theme(axis.text.x = element_text(angle = 90)) +
    geom_bar()
ggsave("filename.pdf")

You can also adjust the size of the font of the labels, or use a legend (which may be a neater way of listing all your labels in order, if there are too many - you can also colour each label differently if you use fill = Species in aes ). You can find out how to set these parameters by typing ?theme , and ggplot2 also has excellent documentation with lots of examples at http://docs.ggplot2.org .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM