Hello you clever R people! I'm trying to create a stack bar plot showing soil thicknesses with a specific background colour and then add labels to the plot that change colour depending on the background colour. I'm very new to R and this is the first time I've attempted something like this. I've worked through several examples and I think I'm getting close but I can't seem to work out how to create a conditional text colour based on the back ground colour. I want something like this example:- https://lara-southard.medium.com/changing-geom-text-color-for-stacked-bar-graphs-in-ggplot-f0e45bfeaa56
My code is messy because it's modified from a worked example Here is my code:-
soil_profile <- cbind.data.frame(
profile = "", # Name of the whole profile
from = c(0,0.41,0.76,1.00,1.45,1.58,1.88), # Beginning of each horizon
to = c(0.41,0.76,1.00,1.45,1.58,1.88,2.48), # End of each horizon
horizon=c('Peaty loam','Loamy peat', 'Humified peat (1)', 'Humified peat (2)', 'Fine sand',
'Pipe bedding and exclusion zone', 'Pipe'), # Name of the horizon
hex = c('#33CCCC', '#008080', '#003366', '#003366', '#F2F2F2', '#A9D18E', '#A9D18E')
)
soil_profile
soil_profile <- soil_profile%>%
mutate(
height = to - from
)
soil_profile
soil_plot<-ggplot(
data = soil_profile,
aes(
x=profile,y=-height, # specify x and y axis
fill=fct_reorder(horizon,to,.desc=TRUE)), # make sure that horizons are on the right order
)+
geom_col(
width=0.8, color= 'white' # Profile width
)
soil_plot
soil_plot<-soil_plot+
scale_fill_manual(
breaks=soil_profile$horizon,
values=soil_profile$hex)
soil_plot
soil_plot<-soil_plot+
guides(fill=FALSE)+ # Hide legend
geom_text(
aes(y=-(from+height/2),label=horizon))
soil_plot
soil_plot+
scale_x_discrete(position = 'top')+ # Move profile name to the top
labs(
title = "",
y = "Depth (meters)",
x=""
)+
theme_minimal()
Here is the graph I get enter image description here and here is the graph I want enter image description here
I want something like this example:- https://lara-southard.medium.com/changing-geom-text-color-for-stacked-bar-graphs-in-ggplot-f0e45bfeaa56