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

标签 r ggplot2 units-of-measurement

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

最佳答案

您可以使用 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)

Resulting plot

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

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")

关于r - 是否可以将 ggplot 与 R 中的单位包一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61209769/

相关文章:

c++ - 用于解析包含单位的字符串的库

r - 具有多个条件的 if 语句更好,还是更多 else if 语句更好?

r - 在 R 中查找给定数据的 "row wise" "Mode"

r - 如何获取未保存的脚本选项卡

r - 在条形图中添加每组的观察数(ggplot2)

C++ boost ublas + units 维数约束

r - R 中的词干提取

r - 在同一个 Shiny 的应用程序中使用 shinyjs 和 ggplot2::autoplot

r - ggplot : How to add a segment with stat_summary

f# - 如何将具有度量单位的小数转换为具有相同单位的 float ?