Stefan L.
Stefan L.

Reputation: 85

ggplot2 and log scale don't show values = 1

I want to plot a diagram with a log scales y axis:

data <- data.frame(x = seq_len(5), y = c(2,1,100,500,30))
ggplot(data) + aes(x,y) + geom_col() + scale_y_log10()

But because the horizontal axis always crosses the vertical axis at y = 1, the bar for y = 1 is never drawn.

enter image description here

I know that log(1) = 0, but can I set the plot base to 0.1 to let the bar start below 1?

Upvotes: 0

Views: 1619

Answers (2)

Allan Cameron
Allan Cameron

Reputation: 173928

Can't you just multiply the values of y by 10 but divide the labels by the same amount?

ggplot(data) + aes(x, y * 10) +  geom_col() + 
  scale_y_log10(labels = function(x) x/10, name = "y")

enter image description here

You could do the same with a histogram:

set.seed(2)
ggplot(data.frame(x = rnorm(1000)), aes(x)) + 
  geom_histogram(aes(y = ..count.. * 10), color = "black", fill = "gold") +
  scale_y_log10(labels = function(x) x/10, name = "count")

enter image description here

Upvotes: 1

teunbrand
teunbrand

Reputation: 37953

An alternative solution is to place the bottom of the bars at -Inf, so that the log10(1) still shows up. This is a bit tricky, because you have to reparameterise the bars as rectangles and get the geom to understand that the -Inf is after scale transformation.

library(ggplot2)

data <- data.frame(x = seq_len(5), y = c(2,1,100,500,30))

ggplot(data) + 
  geom_rect(
    aes(xmin = x - 0.45, xmax = x + 0.45,
        ymin = stage(1, after_scale = -Inf), ymax = y)
  ) +
  scale_y_log10()

Created on 2020-11-03 by the reprex package (v0.3.0)

Upvotes: 1

Related Questions