Closed
Description
Dear devs,
I've encountered behaviour with geom_bar()
which may be a bug. I noticed the behaviour in a bar chart, where the x-axes contained POSIXct dates, while trying to highlight a single year by adding a new layer with a subsetted data.frame
with nrow == 1
. The expected chart is generated when using a data.frame
with length > 1 (see reprex). The behaviour does not ocurr with numeric x values and axis.
The issue may be related to #2047.
Thanks,
Alex
library(ggplot2)
#> Warning: package 'ggplot2' was built under R version 4.2.3
# with posixct axis --------------------------------------------------------
start <- as.POSIXct("2020-01-01")
end <- as.POSIXct("2030-01-01")
dates <- seq(start, end, length.out = 11)
values <- (1:11)
df <- data.frame(date = dates, value = values)
filter_date_single_row <- "2029-01-01"
# assert that we will try to add a df with a single row
if(nrow(df[df$date > as.POSIXct(filter_date_single_row), ]) == 1){
ggplot(df) +
geom_bar(aes(x = date, y = value, fill = "base"), stat = "identity") +
# add single row
geom_bar(
inherit.aes = FALSE,
data = df[df$date > as.POSIXct(filter_date_single_row), ],
aes(x = date, y = value, fill = "add"),
stat = "identity")
}
filter_date_multiple <- "2025-01-01"
# assert that we will try to add a df with more than one row row
if(nrow(df[df$date > as.POSIXct(filter_date_multiple), ]) > 1){
ggplot(df) +
geom_bar(aes(x = date, y = value, fill = "base"), stat = "identity") +
# add single row
geom_bar(
inherit.aes = FALSE,
data = df[df$date > as.POSIXct(filter_date_multiple), ],
aes(x = date, y = value, fill = "add"),
stat = "identity")
}
str(df[df$date > as.POSIXct(filter_date_single_row), ])
#> 'data.frame': 1 obs. of 2 variables:
#> $ date : POSIXct, format: "2030-01-01"
#> $ value: int 11
str(df[df$date > as.POSIXct(filter_date_multiple), ])
#> 'data.frame': 5 obs. of 2 variables:
#> $ date : POSIXct, format: "2025-12-31 19:12:00" "2027-01-01 02:24:00" ...
#> $ value: int 7 8 9 10 11
# with numeric X-Axis -----------------------------------------------------
x <- 1:11
values <- (1:11)
df <- data.frame(x = x, value = values)
# this works
filter_x_single_row <- 10
# assert that we will try to add a df with a single row
if(nrow(df[df$x > filter_x_single_row, ]) == 1){
ggplot(df) +
geom_bar(aes(x = x, y = value, fill = "base"), stat = "identity") +
# add single row
geom_bar(
inherit.aes = FALSE,
data = df[df$x > filter_x_single_row, ],
aes(x = x, y = value, fill = "add"),
stat = "identity")
}
Created on 2024-09-26 with reprex v2.1.1
ggplot2 Version: 3.5.1
R: 4.2.2
Metadata
Metadata
Assignees
Labels
No labels