Closed 83221n4ndr34 closed 1 month ago
This is case 2 of the details section of ?aes_group_order
. Briefly, your discrete x-axis counts towards grouping. If you manually set the groups correctly, all these issues disappear.
library(ggplot2)
df <- data.frame(
time = rep(1:10, each = 4),
category = rep(c("A", "B", "C", "D"), times = 10),
value = c(runif(10, 0, 5), runif(10, 0, 5), runif(10, 0, 5), runif(10, 0, 5))
)
colors <- c("A" = "#ff0000", "B" = "#ff90c7", "C" = "#167b2b", "D" = "#0000ff")
ggplot(df, aes(x = as.character(time), y = value, fill = category, group = category)) +
geom_area(position = "stack") +
scale_fill_manual(values = colors) +
theme_minimal()
Created on 2024-05-29 with reprex v2.1.0
The error message is correct: there wasn't any fill
column left after the incorrect grouping.
I encountered an issue when using
geom_area()
in ggplot2: when the x-axis is discrete, the code either produces an irrelevant warning or fails to plot anything without an informative error message. Here are the details:Discrete X-Axis with Specified Colors
When using
geom_area()
with discrete values for x-axis and specifying fill colors usingscale_fill_manual()
, the code produces the following warning:Discrete X-Axis without specified colors
When using
geom_area()
discrete values for x-axis without specifying fill colors, ggplot2 silently fails to plot anything. There is no warning or error message to indicate the issue.Suggestion
It would be helpful if the library could provide a more informative error message in these scenarios. For example, a message indicating that
geom_area()
does not support discrete x-axes would be very useful for diagnosing the issue.Example code
Below is the demonstration of the problem with the example code.
Plot with Numeric x-Axis (for control)
Plot with Character x-Axis
Same results with Factor x-Axis
Bonus: Forcing Discrete x-Axis to the Right Plot
This plot renders correctly but without x-axis labels.