overlapping axis label depending on the window siz

2019-08-11 00:41发布

问题:

As show in some other questions, in ggplot2 the labels on axis can be overlapped when the windows size was very small and the number of ticks / labels very large:

x <- data.frame(x1=1:100,x2=1:100)
ggplot(x, aes(x1,x2))+geom_point() +
scale_x_continuous(breaks = x1[x1 %% 2 == 0])

In generic plot, the numbber of labels are automaticaly adapted when we change the size of the windows (and all the ticks are drawed):

plot(x1,x2, xaxt="n")
axis(1, at = x1[x1 %% 2 == 0], labels = x1[x1 %% 2 == 0])

So, assuming it nt efficiant to abbreviate labels or to change theyre angle (only small number), is it possible to set up ggplot2 to remove some labels in function of the window size? To force ggplot2 to react as generic plot?

The solution which consist in calculate the number of labels and adapted it to the window size is complicated because it depends on external factor (size of the sceen, dataset used...)

回答1:

Not an automatic adjustment for each possible window size, but idea can be helpful. You can use labels = to suppress some labels:

exclude_labels <- function(x, step) {x[-seq.int(1, length(x), step)] <- ""; x}
ggplot(x, aes(x1,x2))+ geom_point() +
scale_x_continuous(breaks = x$x1[x$x1 %% 2 == 0], 
                   labels = exclude_labels(x$x1[x$x1 %% 2 == 0], 4))



标签: r ggplot2