【发布时间】:2019-11-26 10:25:58
【问题描述】:
我想用 ggplot2 包直观地比较 R 中美国两个州的交通站点的两个数据集。我将它们组合到一个数据框中,显示每年和州的交通站点总数。由于这些数字非常不同,我想比较每个州的人口百分比。首先,这是一个示例 df 以及我到目前为止所取得的成就。我在代码中使用了tidyverse 和lubridate。
df <- data.frame(ID=c("CA-2013-0000001","CA-2014-0000001", "TX-2013-0000001", "TX-2014-0000001"),
State=c("CA", "CA", "TX", "TX"),
Stop_Date=ymd("2013-01-01","2014-01-01", "2013-01-01", "2014-01-01"))
df %>%
group_by(year = year(Stop_Date), state = State) %>%
count() %>%
ggplot(aes(year, n, col = state))+
geom_point(stat = "identity")+
geom_line(stat = "identity")
使用该代码,我得到了一个有两条线的图,每条线都反映了我看到的两种状态。
我想创建完全相同的图,但我想显示与州人口相关的百分比,而不是总数,即population_ca <- 38620000 和population_tx <- 26980000。
我尝试了这两种方法,但每次运行代码时都会返回不同的错误:
df %>%
group_by(year = year(Stop_Date), state = State) %>%
summarise(PercentStopsToPopulation = if_else(state == "CA",
((n()/population_ca)*100),
((n()/population_tx)*100))) %>%
ggplot(aes(year, PercentStopsToPopulation, col = state))+
geom_point(stat = "identity")+
geom_line(stat = "identity")
df %>%
group_by(year = year(Stop_Date), state = State) %>%
summarise(PercentCA = ifelse(state == "CA",((n()/population_ca)*100)),
PercentTX = ifelse(state == "TX", ((n()/population_tx)*100))) %>%
ggplot(aes(year, PercentCA))+
geom_point(stat = "identity")+
geom_line(stat = "identity")+
geom_point(aes(year, PercentTX), stat = "identity")+
geom_line(aes(year, PercentTX), stat = "identity")
我真的希望有人可以帮助我并告诉我我的错误在哪里。 提前谢谢!
【问题讨论】:
-
能否请您再次检查您的数据?我想知道它是否可能遗漏了什么。