I am drawing this graph below and I want to show the differences in annual growth between gross income and net income for different social classes. As you can see when gross and net income go in different directions as in the case of the low-skilled working class, the colors match the legend. However, if annual growth go in the same direction as in the case of the first three bars, then we see growth income in red, and net income in orange. Is there a way to keep the colors contrasting as in the last column on the right even when they overlap?
Here is the graph:
Here is a simplified version of the code:
ggplot(df, aes(x=year, y=annual_chg, fill=income,color=income))
geom_col(position = "identity", alpha = 1/2,colour= "black")
facet_wrap(~Class,nrow=1)
theme_classic() xlab(NULL) ylab(NULL)
scale_color_manual(values = c("blue4","red4"))
scale_fill_manual(values=c("blue4","red4"))
Here is the data:
df= structure(list(year = c(2018, 2018, 2018, 2018, 2018, 2018, 2018,
2018), annual_chg = c(-0.66, 0.34, 0.59, 1.54, -0.26, 0.49, 0.66,
1.62), Class = structure(c(4L, 3L, 2L, 1L, 4L, 3L, 2L, 1L), .Label = c("Upper-middle class",
"Middle class", "Skilled working class", "Low-skilled working class"
), class = "factor"), income = c("gross income", "gross income",
"gross income", "gross income", "net income", "net income", "net income",
"net income")), row.names = c(NA, -8L), class = c("tbl_df", "tbl",
"data.frame"))
CodePudding user response:
It sounds like you want to modify the data so that when we see a comparatively larger value, the delta should be plotted but not the part that overlaps with the smaller value it supercedes.
I'd do this by pre-processing the data first to find the deltas so we can plot those instead of the original values.
library(dplyr); library(forcats); library(ggplot2)
df %>%
group_by(Class, year) %>%
arrange(abs(annual_chg)) %>%
mutate(increm = annual_chg - lag(annual_chg, default = 0)) %>%
mutate(income = forcats::fct_rev(income)) %>%
ungroup() %>%
ggplot(aes(x=year, y=increm, fill=income, color=income))
geom_col(position = "stack", alpha = 1/2, color = "black")
facet_wrap(~Class,nrow=1)
theme_classic() xlab(NULL) ylab(NULL)
scale_x_continuous(breaks = scales::breaks_width(1))
scale_color_manual(values = c("blue4","red4"))
scale_fill_manual(values=c("blue4","red4"))