【问题标题】:Plotting pre-computed statistics on POSIX dates with ggplot's geom_boxplot使用 ggplot 的 geom_boxplot 绘制关于 POSIX 日期的预计算统计数据
【发布时间】:2015-06-16 17:35:39
【问题描述】:

我正在尝试创建一系列显示日期值分布的箱线图。我使用data.table 计算分位数,然后将它们提供给ggplot 进行绘制。但是,当我尝试绘制它们时,我收到一条错误消息,提示“错误:'/' not defined for "POSIXt" objects”。

这是一个使用来自lubridate 的数据的可重现示例:

library(data.table)
library(ggplot2)
library(lubridate)

# Load data from the lubridate library
data(lakers)

# create POSIX date variable
lakers <- within(lakers, posix.date <- ymd(date))
lakers <- data.table(lakers, key = "player")

# Calculate quantiles of dates by player
# follows post at http://stackoverflow.com/questions/14758566/how-can-i-use-functions-returning-vectors-like-fivenum-with-ddply-or-aggregate
Tukeys.five <- c("Min","Q1","Med","Q3","Max") 
plot.stats <- lakers[
    ,
    {quant <- as.list(quantile(posix.date, prob = seq(0,1, by = 0.25),
                               names = F))
    setattr(quant, 'names', Tukeys.five)
    quant},
    by = player
    ]

# Now attempt to plot this with ggplot
ggplot(plot.stats, aes(x = player, ymin = Min, lower = Q1, middle = Med, 
                       upper = Q3, max = Max, group = player)) +
  geom_boxplot(stat = "identity") + coord_flip() 
# Error: '/' not defined for "POSIXt" objects
# In addition: Warning message:
# In loop_apply(n, do.ply) :
#   position_dodge requires constant width: output may be incorrect

任何想法为什么我会收到这个错误,或者如何解决它?我尝试将日期转换为数值,并且绘制正确,但是轴只显示数值而不是日期。

【问题讨论】:

    标签: r ggplot2 data.table lubridate


    【解决方案1】:

    看起来geom_boxplot 的代码会进行除法以尝试计算框宽。据我所知,分支似乎是不可避免的。一个 hack-y 解决方法是实际定义日期时间值的除法。

    `/.POSIXt`<-function(e1,e2) as.numeric(e1)/as.numeric(e2)
    

    在您的代码似乎产生所请求的情节之前运行它。测试

    `/.POSIXt`<-function(e1,e2) as.numeric(e1)/as.numeric(e2)
    ggplot(plot.stats[1:10,], aes(x = player, ymin = Min, lower = Q1, middle = Med, 
                           upper = Q3, max = Max, group = player)) +
      geom_boxplot(stat = "identity") + coord_flip() 
    

    【讨论】:

    • 哇,谢谢!您发现并解决了这个解决方法,这让我印象深刻。
    猜你喜欢
    • 2021-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-23
    • 1970-01-01
    • 1970-01-01
    • 2011-12-01
    相关资源
    最近更新 更多