ekatko1
ekatko1

Reputation: 313

Is it possible to use ggplot with the units package in R?

The units library simplifies working with units. Plotting with units works fine with base plot, but not with ggplot, as far as I know. Any suggestions?

library(units)

# Take cars data frame: stopping dist (ft) vs speed (mph)
plot(cars)

# units + base plot
Distance = set_units(cars$dist, ft)
Speed = set_units(cars$speed, mph)
plot(x=Speed, y=Distance) #Clean

# units + ggplot
library(ggplot2)
df = cars
df$Disance = set_units(df$dist, ft)
df$Speed = set_units(df$speed, mph)

qplot(x=Speed, y=Distance, data=df)
# Error in Ops.units(x, range[1]) : 
#   both operands of the expression should be "units" objects

Upvotes: 2

Views: 928

Answers (1)

Romain
Romain

Reputation: 21888

You can use ggforce that solves this problem.
More specifically, see scale_unit.

# install.packages("ggforce")
library(ggplot2)
library(ggforce)

df = cars
df$Distance = set_units(df$dist, ft)
df$Speed = set_units(df$speed, mph)

qplot(x=Speed, y=Distance, data=df)

Resulting plot

You obtain the same result like this to avoid to avoid to transform the data.

qplot(x=speed, y=dist, data=cars) +
    scale_x_unit(unit = 'mph') +
    scale_y_unit(unit = 'ft')

Notes

  • This answer gives me the idea to write a post on this topic to play with units and plots.
  • There is currently an issue with the latest version of ggplot that drops axis values. It's possible to switch to the development version while waiting for the new version to be released: devtools::install_github("thomasp85/ggforce").

Upvotes: 7

Related Questions