是否可以将 ggplot 与 R 中的单位包一起使用?

eka*_*ko1 2 r units-of-measurement ggplot2

单位库简化了单位的使用。据我所知,使用单位绘图适用于基本图,但不适用于 ggplot。有什么建议?

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
Run Code Online (Sandbox Code Playgroud)

Rom*_*ain 5

您可以使用ggforce它来解决这个问题。
更具体地说,请参阅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)
Run Code Online (Sandbox Code Playgroud)

结果图

您获得与此相同的结果以避免避免转换数据。

qplot(x=speed, y=dist, data=cars) +
    scale_x_unit(unit = 'mph') +
    scale_y_unit(unit = 'ft')
Run Code Online (Sandbox Code Playgroud)

笔记

  • 这个答案让我有想法写一篇关于这个主题的帖子来玩单位和情节。
  • 当前最新版本的 ggplot存在一个问题,该问题会降低轴值。可以在等待新版本发布的同时切换到开发版本:devtools::install_github("thomasp85/ggforce").