silent_hunter
silent_hunter

Reputation: 2508

Use small font with ggplot2

I try to make plot with ggplot. So evereting is ok with plot in plotting in R-Studio. But problem arise when I try to make PDF and output this plot outside from R. Namely the letters overlap themself. You can see on pic below, I already marked with yellow color.

enter image description here

For plotting I use this lines of code

# Plotting with ggplot2
        p<-ggplot(data_plot, aes(x=y, y=z)) +
           stat_pareto(point.color = "red",
                      point.size = 3,
                      line.color = "black",
                      size.line = 1,
                      bars.fill = c("blue", "orange")
          ) +
          xlab(' ') +
          ylab('')
        
       # Output in pdf
        pdf(file=paste("out.pdf",sep=""),width=10, height=5)
        
        op <- par(mgp=c(1,0,0),mar=c(2, 2, 1, 1),# Room for the title and legend: 1_bottom,2_left,3_up,4_right
                  mfrow=c(1,2))
        
        plot(p)

So can anybody help in order to get better value of x axis, letters with smaller font or whatever and fix this error ?

Upvotes: 0

Views: 318

Answers (2)

Allan Cameron
Allan Cameron

Reputation: 173803

The latest version of ggplot allows you to dodge axis labels by specifying n.dodge in guide_axis to fix overlapping x axis labels.

Compare this plot:

library(ggplot2)

p <- ggplot(data.frame(y = 1/1:10, x = paste("long label", 0:9)), aes(x, y)) +
      geom_col(fill = "royalblue")
p

to this:

p + scale_x_discrete(guide = guide_axis(n.dodge = 2))

Upvotes: 5

Paul
Paul

Reputation: 2977

Please, find below some ideas that helped me a lot when dealing with font sizes. After trying a lot with base plot systems I always come back to ggplot and its powerful theme() and ggsave() functions. You are making your plot with ggplot, why not stick with it until the end? ;)

library(ggplot2)

ggplot(data = iris, aes(x = Species, y = Sepal.Width)) +
  geom_bar(stat = "identity") +
  theme(axis.text.x = element_text(size = 4)) # change here the size of the text

ggsave(filename = "test.pdf", device = "pdf", width = 5, height = 5, units = "cm", dpi = 500) # use this function to save your plot
# much easier to control end dimensions and resolution.
# Here I plot a 5cm x 5 cm plot with font size of 4 pt on x-axis labels

Upvotes: 1

Related Questions