sergiouribe
sergiouribe

Reputation: 231

columns are not aligned with the data in ggplot geom_col

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

Upvotes: 2

Views: 292

Answers (2)

George Savva
George Savva

Reputation: 5336

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.

Upvotes: 1

Kra.P
Kra.P

Reputation: 15143

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

Upvotes: 1

Related Questions