I have a time series with different variables and different units that I want to display on the same plot.
ggplot does not support multiple axis (as explained here), so I followed the advice and tried to plot the curves with facets:
x <- seq(0, 10, by = 0.1) y1 <- sin(x) y2 <- sin(x + pi/4) y3 <- cos(x) my.df <- data.frame(time = x, currentA = y1, currentB = y2, voltage = y3) my.df <- melt(my.df, id.vars = "time") my.df$Unit <- as.factor(rep(c("A", "A", "V"), each = length(x))) ggplot(my.df, aes(x = time, y = value)) + geom_line(aes(color = variable)) + facet_wrap(~Unit, scales = "free_y", nrow = 2)
Here is the result:
The thing is that there is only one y label, saying "value" and I would like two: one with "Currents (A)" and the other one with "Voltage (V)".
Is this possible?
While facet_grid shows the labels at the margins of the facet plot, facet_wrap creates a label for each plot panel.
To alter the labels on the axis, add the code +labs(y= "y axis name", x = "x axis name") to your line of basic ggplot code. Note: You can also use +labs(title = "Title") which is equivalent to ggtitle .
Facet labelsSet the strip. text element in theme() to element_blank() . Setting strip. text to element_blank() will remove all facet labels.
To increase the X-axis labels font size using ggplot2, we can use axis. text. x argument of theme function where we can define the text size for axis element.
In ggplot2_2.2.1 you could move the panel strips to be the y axis labels by using the strip.position
argument in facet_wrap
. Using this method you don't have both strip labels and different y axis labels, though, which may not be ideal.
Once you've put the strip labels to be on the y axis (the "left"), you can change the labels by giving a named vector to labeller
to be used as a look-up table.
The strip labels can be moved outside the y-axis via strip.placement
in theme
.
Remove the strip background and y-axis labels to get a final graphic with two panes and distinct y-axis labels.
ggplot(my.df, aes(x = time, y = value) ) + geom_line( aes(color = variable) ) + facet_wrap(~Unit, scales = "free_y", nrow = 2, strip.position = "left", labeller = as_labeller(c(A = "Currents (A)", V = "Voltage (V)") ) ) + ylab(NULL) + theme(strip.background = element_blank(), strip.placement = "outside")
Removing the strip from the top makes the two panes pretty close together. To change the spacing you can add, e.g., panel.margin = unit(1, "lines")
to theme
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With