Giovanni Azua Giovanni Azua - 1 month ago 5
R Question

geom_bar produces x-axis tick text aliased/distorted

The following minimal example reproduces the issue to a minor degree ... I noticed that the distortion depends on how much data is stacked up whereas if there is no stacked up data then there is no aliasing/distortion. The y-axis tick text is never affected only the x-axis tick text. The color/boldness difference between the x-axis tick text is also very noticeable.

library(ggplot2)

x <- c(1111, 2222, 3333, 1111, 1111, 3333, 3333, 1111, 3333, 1111, 2222, 1111, 3333, 1111, 1111)
y <- c(11, 12, 13, 12, 13, 12, 13, 12, 13, 12, 13, 12, 13, 12, 13)
z <- c('a', 'b', 'c', 'a', 'b', 'a', 'b', 'c', 'a', 'a', 'b', 'c', 'a', 'c', 'a')
df <- data.frame(x, y, z)

g <- ggplot(data=df, aes(x, y, fill=z)) +
geom_bar(stat="identity") + scale_x_continuous(breaks=df$x)
g


I then get the 3333 axis somewhat aliased/distorted and noticeably darker than the 1111 and 2222:

aliased/distorted 3333

Is there a way to post-process the plot and fix this?

I have tried without success:

library(extrafont)
ggsave(filename='myplot.pdf', plot=g)
embed_fonts('myplot.pdf')


UPDATE: If I remove
breaks=df$x
from
scale_x_continuous(breaks=df$x)
then the distortion is gone ... but I need the breaks otherwise it will not always show every x-axis tick and I need it.

Any ideas how to go around this issue and keep all the breaks without distortion?

Answer

Your breaks are being overplotted on top of each other for every time they occur in your data. This creates the "distortion" you see. Easily remedied by using unique(df$x) instead of df$x as the breaks.

Comments