【问题标题】:Is it possible to use ggplot with the units package in R?是否可以将 ggplot 与 R 中的 units 包一起使用?
【发布时间】:2020-07-27 07:17:10
【问题描述】:

单位库简化了单位的使用。据我所知,使用单位绘图适用于基本图,但不适用于 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

【问题讨论】:

    标签: r ggplot2 units-of-measurement


    【解决方案1】:

    您可以使用解决此问题的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)
    

    你得到同样的结果是为了避免避免转换数据。

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

    注意事项

    • 这个答案让我想到写一个post 来讨论这个主题来玩单位和情节。
    • 目前有一个 issue 带有最新版本的 ggplot 删除轴值。可以在等待新版本发布时切换到开发版本:devtools::install_github("thomasp85/ggforce")

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-08-07
      • 2017-11-24
      • 1970-01-01
      • 1970-01-01
      • 2021-11-12
      • 2016-04-01
      • 2011-01-20
      相关资源
      最近更新 更多