I've found lots of great documentation for how to insert special characters and Greek letters into axis labels in ggplot in R, but nothing for pasting legend colors into the axis labels. I am creating a graph with a slightly complicated x-axis, and a collaborator suggested formatting the axis with a colored square (identical to the figure legend) in the axis label text so readers can reference which axis label refers to which data series.
Here's what the figure legend currently looks like:
[ORANGE SQUARE] Series 1
[BLUE SQUARE] Series 2
And here's what I'd like the x-axis label to look like:
Extent in km [ORANGE SQUARE] or km/yr [BLUE SQUARE]
Is it possible to do this kind of graphical manipulation in R, or do I need to create this kind of label in some other image processing software? Here's the plotting code I'm using, with some fake data:
SERIES1 <- as.data.frame(sample(1:100, 100, replace=TRUE)) %>% mutate(source="SERIES1")
SERIES2 <- as.data.frame(sample(1:1000, 100, replace=TRUE)) %>% mutate(source="SERIES2")
SERIES3 <- as.data.frame(sample(1:10000, 100, replace=TRUE)) %>% mutate(source="SERIES3")
colnames(SERIES1) <- c("value","source")
colnames(SERIES2) <- c("value","source")
colnames(SERIES3) <- c("value","source")
gg_df <- rbind(SERIES1, SERIES2, SERIES3)
fig1A <- ggplot(gg_df) +
geom_density(alpha=0.5, size=0.2, aes(x=value, y=..scaled.., fill=factor(source, labels=c('SERIES1','SERIES2','SERIES3')))) +
scale_x_continuous(limits=c(0,16000), breaks=c(seq(0, 16000, by=2000))) +
labs(x='Extent (km) or (km/dec)',y='Density') +
theme_bw() +
theme(legend.position=c(0.8, 0.85), legend.title=element_blank()) +
scale_fill_brewer(type='qual',palette='Dark2')