【问题标题】:How to plot a count of N/As over time in ggplot2如何在ggplot2中随时间绘制N / As的计数
【发布时间】:2018-01-25 16:20:49
【问题描述】:

我有一个数据集,其中一个字段包含日期,另一个字段包含 N/As。我将其创建为更大数据集的子集,因为我需要查看 N/As 的数量是来自一个时间段还是更均匀地分布在所有时间。

我的数据如下所示:

User_id |    Date    | app_version
001     | 2016-01-03 | <NA>
002     | 2016-03-03 | <NA>
003     | 2016-02-22 | <NA>
004     | 2016-04-15 | <NA>
...

我想做的是在 X 轴上绘制一个带有时间的折线图,在 Y 轴上绘制 NA 的数量。

提前致谢。

【问题讨论】:

  • 首先修复您的数据,例如library(tidyverse); df %&gt;% group_by(Date) %&gt;% summarise(app_version = sum(is.na(app_version))) %&gt;% ggplot(aes(Date, app_version)) + geom_line()

标签: r ggplot2


【解决方案1】:

使用dplyrggplot2:对数据进行相应的分组,汇总并计算 NA 值的数量,然后进行绘图。 (在这种情况下,我按Date 分组并添加geom_point 以显示每个日期。)

library(dplyr)
library(ggplot2)

df %>% 
  group_by(Date) %>% 
  summarize(na_count = sum(is.na(app_version))) %>% 
  ggplot(aes(x = Date, y = na_count)) +
  geom_line() +
  geom_point()

【讨论】:

  • 感谢您的回复,但我收到此错误消息:Error in grouped_df_impl(data, unname(vars), drop) : Column install_date` is of unsupported class POSIXlt/POSIXt`
  • 听起来您需要正确格式化install_date,请尝试使用as.Dateas.POSIXct。见:stackoverflow.com/questions/30063190/…
  • 谢谢,我使用的是as.POSIXct(),但使用了错误的df :S。它现在正在工作。
【解决方案2】:

你的数据库

User_id<-c("001","002","003","004")
Date<-c("2016-01-03","2016-03-03","2016-02-22","2016-04-15")
app_version<-c(NA,NA,NA,NA)

db<-data.frame(cbind(User_id,Date,app_version))

你的图表

plot(table(db[is.na(db$app_version),"Date"]),type="l")

【讨论】:

  • 感谢您的回复,但我收到此错误:Error in table(na_df[is.na(na_df$app_version), "install_date"]) : 'names' attribute [75] must be the same length as the vector [11]
  • 请添加更多关于代码生成错误的详细信息
【解决方案3】:
library(plyr)
#create a field that breaks the dates down to just year & month
#You can break it down by year if you'd like
df$yr_mth<-substr(df$Date, 1, 7)
#summarize the number of NAs per year_month 
df1<-ddply(df, .(yr_mth), summarize, 
    num_na=length(which(is.na(app_version))))
#plot yr_mth on x, num_na on y
ggplot(data=df1, aes(x=as.Date(yr_mth), y=num_na))+
    geom_point()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-27
    • 2017-12-11
    • 1970-01-01
    • 2016-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多