2

plotting some data to a figure with numerical data, one would expect the column border to line up with the grid. However, when plotting this data, you can see that there are some that line up correctly (10, 5), but others don't (2, 1).

Is this a bug or a feature?

geom_col columns not aligned with grid

Reproducible example

library(tidyverse, scales)

The data

x1 <- c("a", "b", "c", "d", "e")
y1 <- c(1, 10, 2, 1, 5)
xy <- data.frame(x1, y1)

The plot

xy %>% 
  ggplot(aes(x = fct_reorder(x1, desc(y1)),
             y = y1)) +
  geom_col() +
  geom_text(aes(label = y1), vjust = 1.5, colour = "white") # to show the numbers

Some experiments

Correct

xy %>% 
  ggplot(aes(x = fct_reorder(x1, desc(y1)),
             y = y1)) +
  geom_col() +
  scale_y_continuous(minor_breaks = seq(0, 10, .5)) +
  # scale_y_continuous(labels = scales::number_format(accuracy = .5)) +
  geom_text(aes(label = y), vjust = 1.5, colour = "white")

correct aligned

But then

Incorrect

xy %>% 
  ggplot(aes(x = fct_reorder(x1, desc(y1)),
             y = y1)) +
  geom_col() +
  scale_y_continuous(minor_breaks = seq(0, 10, .5)) +
  scale_y_continuous(labels = scales::number_format(accuracy = .5)) +
  geom_text(aes(label = y), vjust = 1.5, colour = "white")

incorrect

Also incorrect

xy %>%
  ggplot(aes(x = fct_reorder(x1, desc(y1)),
             y = y1)) +
  geom_col() +
  scale_y_continuous(minor_breaks = seq(0, 10, 1),
                     labels = scales::number_format(accuracy = 1)) +
  geom_text(aes(label = y1), vjust = 1.5, colour = "white")

incorrect also ggplot geom_col

sergiouribe
  • 221
  • 1
  • 3
  • 11

2 Answers2

1

That 2 in yaxis is 2.5 and near 1 is 1.25 not 1.

xy %>% 
  ggplot(aes(x = fct_reorder(x1, desc(y1)),
             y = y1)) +
  geom_col() +
  scale_y_continuous(breaks = seq(0,10,2)) +
  geom_text(aes(label = y1), vjust = 1.5, colour = "white")

enter image description here

  xy %>% 
    ggplot(aes(x = fct_reorder(x1, desc(y1)),
               y = y1)) +
    geom_col()

enter image description here

I don't know why you add accuracy = 1 but take a look at plot below.

xy %>% 
  ggplot(aes(x = fct_reorder(x1, desc(y1)),
             y = y1)) +
  geom_col() +
  scale_y_continuous(breaks = seq(0,10,2))

enter image description here

Park
  • 14,771
  • 6
  • 10
  • 29
1

This is a rounding error caused by your scales_y_continuous call. Use

ggplot(xy,aes(x = fct_reorder(x1, desc(y1)),
           y = y1)) +
  geom_col() +
  scale_y_continuous(breaks=c(0,2,5,8,10)) +
  geom_text(aes(label = y1), vjust = 1.5, colour = "white")

To get what you want.

George Savva
  • 4,152
  • 1
  • 7
  • 21