I am trying to just mark the max and min of each x-axis in a faceted ggplot. I have several facets with different x scales and the same y scale, and the x axis tick labels overlap each other. Rather than having to manually determine the limits and breaks for each facet x axis, I am looking for a way to just label the min and max values for each.
Code using example data of the CO2
dataset (see ?CO2
):
CO2$num <- 1:nrow(CO2)
library(reshape2)
CO2.melt <- melt(CO2,
id.var=c("Type",
"Plant",
"Treatment",
"num"))
CO2.melt <- CO2.melt[order(CO2.melt$num),]
library(ggplot2)
ggplot(CO2.melt,
aes(x = value,
y = num)) +
geom_path(aes(color = Treatment)) +
facet_wrap( ~ variable, scales = "free_x",nrow=1)
Purpose is to replicate well log displays such as this one.
When you want to implemented this for the tick-labels, the use of
scales = "free_x"
in a faceted plot makes this hard to automate this. However, with a bit of tinkering and the help of several other packages, you could also use the following approach:1) Summarise the data in order to get an idea which tick-labels / breaks you need on the x-axis:
which gives:
2) Create break vecors for each facet:
3) Create the facets:
4) Extract the legend into a separate object:
5) Create the final plot:
which results in:
A possible alternative solution to do this automatically, is either use
geom_text
orgeom_label
. An example to show how you can achieve this:which gives:
You can also get the minimum and maximum values on the fly inside
ggplot
(credit to @eipi10). Another example usinggeom_label
:which gives:
Edit Updating to ggplot2 ver 3.0.0
This approach modifies the labels in the ggplot build data (i.e.,
ggplot_build(plot)
). I've removed the x-axis expansions so that the maximum and minimum values fall on the panel boundaries.