是否可以将 ggplot 与 R 中的单位包一起使用?
Is it possible to use ggplot with the units package in R?
单位库简化了使用单位的工作。据我所知,使用单位绘图可以很好地处理基本图,但不适用于 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)
你得到这样相同的结果以避免避免转换数据。
qplot(x=speed, y=dist, data=cars) +
scale_x_unit(unit = 'mph') +
scale_y_unit(unit = 'ft')
备注
单位库简化了使用单位的工作。据我所知,使用单位绘图可以很好地处理基本图,但不适用于 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)
你得到这样相同的结果以避免避免转换数据。
qplot(x=speed, y=dist, data=cars) +
scale_x_unit(unit = 'mph') +
scale_y_unit(unit = 'ft')