Reputation: 313
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
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)
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')
devtools::install_github("thomasp85/ggforce")
.Upvotes: 7