Reputation: 231
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?
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
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")
But then
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")
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")
Upvotes: 2
Views: 292
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
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")
xy %>%
ggplot(aes(x = fct_reorder(x1, desc(y1)),
y = y1)) +
geom_col()
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))
Upvotes: 1