if (requireNamespace("ggplot2", quietly=TRUE)) {
library(ggplot2)
mtcars$consumption <- set_units(mtcars$mpg, mi / gallon)
mtcars$power <- set_units(mtcars$hp, hp)
# Use units encoded into the data
ggplot(mtcars) +
geom_point(aes(power, consumption))
# Convert units on the fly during plotting
ggplot(mtcars) +
geom_point(aes(power, consumption)) +
scale_x_units(unit = "W") +
scale_y_units(unit = "km/l")
# Resolve units when transforming data
ggplot(mtcars) +
geom_point(aes(power, 1 / consumption))
# Reverse the y axis
ggplot(mtcars) +
geom_point(aes(power, consumption)) +
scale_y_units(trans="reverse")
}
Run the code above in your browser using DataLab