Home > Net >  How to set a fixed width of Y axis in R ggplot plots?
How to set a fixed width of Y axis in R ggplot plots?

Time:11-05

Let see I have the following two plots.

library(data.table)
library(ggplot2)


df_one <- data.table(
  x = c(1, 1, 3),
  y = c(10, 20, 30)
)

df_two <- data.table(
  x = c(1, 2, 3),
  y = c(1000, 1600, 3100)
)    

df_one %>% ggplot(aes(x, y))   geom_point()   geom_line()
df_two %>% ggplot(aes(x, y))   geom_point()   geom_line()

The values on Y axis are different by width. How adjust two plots to have the same width of labels on Y if we do not know info about each data sets. For example, if we would like to set width as a fixed number of chars (10 or 15).

Thanks

CodePudding user response:

You can add a custom labeling function in scale_y_continuous.

For example, this addition to the plot makes the y axis labels a fixed width of 10 characters by adding spaces to the front.

df_one %>% ggplot(aes(x, y))   geom_point()   geom_line()  
  scale_y_continuous(labels = function(x) formatC(x, width = 10))

  
df_two %>% ggplot(aes(x, y))   geom_point()   geom_line()  
  scale_y_continuous(labels = function(x) formatC(x, width = 10))

Of course, the panels may still not line up perfectly because you are not using a monospaced font. This means that the spaces and numbers will have varying widths on the screen even if they are the same number of characters long.

If you use a mono font, this will give perfect alignment:

df_one %>% ggplot(aes(x, y))   geom_point()   geom_line()  
  scale_y_continuous(labels = function(x) formatC(x, width = 6))  
  theme(axis.text = element_text(family = "mono"))

  
df_two %>% ggplot(aes(x, y))   geom_point()   geom_line()  
  scale_y_continuous(labels = function(x) formatC(x, width = 6))  
  theme(axis.text = element_text(family = "mono"))

Created on 2021-11-04 by the reprex package (v2.0.0)

  • Related