这里有两列,它们都是因子变量。第一个问题是囚犯的种族,第二个问题是他们是否复习。我想画出按种族划分的累犯率。我应该如何做到这一点?
我试过这个:
df %>%
group_by(race, Recidivated) %>%
summarize(count = n()) %>%
arrange (-count) %>%
ggplot(aes(reorder(race, count, FUN = max),
count, fill = race)) +
geom_col() +
coord_flip() +
scale_fill_manual(values=palette_9_colors) +
theme(legend.position = "none") +
labs(x = "Charge", y = "Count",
title="Recidivism by Rates",
subtitle= "Broward County - Source: Propublica",
caption="UrbanSpatialAnalysis.com") +
plotTheme()
结果是一个计算每个种族数量的直方图。如何获得按种族划分的累犯率可视化图?非常感谢。
以下是一些数据!
> head(df)
sex age age_cat race priors_count two_year_recid
1 Male 69 Greater than 45 Other 0 0
2 Male 34 25 - 45 African-American 0 1
3 Male 24 Less than 25 African-American 4 1
4 Male 44 25 - 45 Other 0 0
5 Male 41 25 - 45 Caucasian 14 1
6 Male 43 25 - 45 Other 3 0
r_charge_desc c_charge_desc
1 Aggravated Assault w/Firearm
2 Felony Battery (Dom Strang) Felony Battery w/Prior Convict
3 Driving Under The Influence Possession of Cocaine
4 Battery
5 Poss of Firearm by Convic Felo Possession Burglary Tools
6 arrest case no charge
c_charge_degree r_charge_degree juv_other_count length_of_stay
1 F 0 1
2 F (F3) 0 10
3 F (M1) 1 1
4 M 0 1
5 F (F2) 0 6
6 F 0 1
Recidivated
1 notRecidivate
2 Recidivate
3 Recidivate
4 notRecidivate
5 Recidivate
6 notRecidivate
race <- sample(c("A", "B", "C", "D"), size = 100, replace = T)
recidivated <- sample(c(TRUE, FALSE), size = 100, replace = T)
df <- data.frame(race, recidivated)
df %>% group_by(race) %>% summarize(recidRate = mean(recidivated)) %>% ggplot(aes(race, recidRate)) + geom_bar(stat = "identity")
如果Recidivated是逻辑变量,则应使用TRUE或FALSE;对于logicals,mean((是TRUE的比例。
希望这有帮助:(