1

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

Andrii
  • 2,843
  • 27
  • 33
  • 1
    Does this answer your question? [How to get identical panel width with different y-axis text lengths](https://stackoverflow.com/questions/34694632/how-to-get-identical-panel-width-with-different-y-axis-text-lengths) – Dubukay Nov 04 '21 at 17:40
  • not exactly. but thanks – Andrii Nov 04 '21 at 17:41
  • How about this one? [How can I add variable size y-axis labels in R with ggplot2 without changing the plot width?](https://stackoverflow.com/questions/22942977/how-can-i-add-variable-size-y-axis-labels-in-r-with-ggplot2-without-changing-the?rq=1) – Dubukay Nov 04 '21 at 17:43

1 Answers1

2

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)

Allan Cameron
  • 147,086
  • 7
  • 49
  • 87