如何在 R 中随时间绘制 TRUE 值?

How do I plot TRUE values over time in R?

例如我有这样一个数据框:

Year|Value
2013|TRUE
2013|TRUE
2013|TRUE
2013|TRUE
2013|FALSE
2013|FALSE
2013|TRUE
2013|FALSE
2014|TRUE
2014|FALSE
2014|FALSE
2014|TRUE
2015|TRUE
2015|TRUE
2015|FALSE
2015|FALSE
2015|TRUE
2015|TRUE

我想绘制每年真相总量的折线图。

我试过了

data <- data.frame('t'=year, 'a'=Value)
plot(data)

...但它在 x 轴和 y 轴上给出年份 0 或 1(是真还是假。而不是每年 TRUE 的数量。

I want to plot a line graph of total amounts of truth per year.

诀窍在于转换您的数据以显示您希望您的情节显示的内容:每年的真实 count,而不是每个观察到的年份布尔值。

这里有一个 dplyr 减少数据的方法。它筛选 TRUE 值,然后计算每年出现的 TRUE 值的行数。

减少

library(dplyr)
library(ggplot2)

tab = structure(list(Year = c(2013L, 2013L, 2013L, 2013L, 2013L, 2013L, 2013L, 2013L, 2014L, 2014L, 2014L, 2014L, 2015L, 2015L, 2015L, 2015L, 2015L, 2015L), Value = c(TRUE, TRUE, TRUE, TRUE, FALSE, FALSE, TRUE, FALSE, TRUE, FALSE, FALSE, TRUE, TRUE, TRUE, FALSE, FALSE, TRUE, TRUE)), .Names = c("Year", "Value"), class = "data.frame", row.names = c(NA, -18L))
tab_sum = tab %>% group_by(Year) %>%
  filter(Value) %>%
  summarise(trues = n()) 
# Source: local data frame [3 x 2]
# 
#    Year trues
#   (int) (int)
# 1  2013     5
# 2  2014     2
# 3  2015     4

情节

现在数据中的每一行都为绘图提供了 xy 对:

ggplot(tab_sum, aes(Year, trues)) + geom_line()

听起来您想创建真值的直方图,对吗?如果是这样,这是最简单的方法:

正在重新创建您的数据集:

year = c(2013, 2013, 2013, 2013, 2013, 2013, 2013, 2013, 
     2014, 2014, 2014, 2014, 
     2015, 2015, 2015, 2015,2015, 2015) 

value = c(TRUE, TRUE, TRUE, TRUE, FALSE, FALSE, TRUE, FALSE, 
      TRUE, FALSE, FALSE, TRUE, 
      TRUE, TRUE, FALSE, FALSE, TRUE, TRUE) 

data <- data.frame('year'=year, 'value'=value)

data$year_factor<-as.factor(as.character(data$year))

data$year_date<-as.Date(as.character(data$year), "%Y")

基本上你要求计算每年的真实值 所以我们将分割我们的数据集,所以它只包含真值:

shortdata <-data[data$value,]

丑陋的版本:

hist(shortdata$year_date, breaks = 3, freq = T)

粗糙但稍微漂亮一点的版本:

qplot(shortdata$year)

但是,好吧,你想要一个线图版本。以下是您的操作方法。

折线图版本:

require(plyr)

freqdf = ddply(shortdata, .(year_factor), summarize, 
               freq = length(year_factor))

freqdf$year_factor <-as.numeric(as.character(freqdf$year_factor))

require(ggplot2)
ggplot(data=freqdf, aes(x=year_factor, y=freq))+geom_line()+
  scale_y_continuous(limits=c(0, 6))+
  ggtitle("True Values Over Three Years")

希望对您有所帮助!祝你绘图顺利!