gpt4 book ai didi

r - 在 ggplot 中使用 ..prop.. 时如何为条形图着色?

转载 作者:行者123 更新时间:2023-12-02 07:57:09 24 4
gpt4 key购买 nike

我正在尝试为 ggplot 上显示比例的条形图着色。我使用以下方式调用该图:

v2 <- ggplot(data = Visual2_Data, 
mapping = aes(x = violation, y = ..prop.., group = 1, fill = violation)) +
geom_bar() +
facet_grid(~driver_race) +
scale_fill_manual(values = c("red", "green", "yellow", "blue", "pink", "purple"))+
theme(axis.text.x = element_text(angle=90))

我的结果如下:

尽管使用了 fillscale_fill_manual,条形图仍然是默认颜色。

一旦我使用 ..count.. 作为 y 变量而不是 ..prop.. 并删除 group = 1 :

v2 <- ggplot(data = Visual2_Data, 
mapping = aes(x = violation, y = ..count.., fill = violation)) +
geom_bar() +
facet_grid(~driver_race) +
scale_fill_manual(values = c("red", "green", "yellow", "blue", "pink", "purple"))+
theme(axis.text.x = element_text(angle=90))

我得到以下信息:

这就是我想要的,除了我想使用 y = ..prop..group = 1 在第一个图中使用这些颜色,而不是使用y = ..counts..。那么有办法做到这一点吗?

提前致谢

为了重现性:

我必须注意,这是一个相对较大的数据集。

我使用来自此来源的科罗拉多州数据:

https://openpolicing.stanford.edu/data/

我整理了一下:

data <- read_csv() #insert data here

Visual2_Data <- data %>%
subset(out_of_state == FALSE) %>%
select(county_name, county_fips, police_department, driver_gender,
driver_age, driver_race, violation, search_conducted,
contraband_found, stop_outcome, is_arrested) %>%
drop_na(county_name) %>%
filter(driver_race != "Other",
violation %in% c("Lights", "Speeding", "Safe movement", "License",
"Seat belt", "Registration/plates"))

# After this I used the code for v2 which already is described above.

v2 <- ggplot(data = Visual2_Data, etcetera)

最佳答案

如果将 fill = ... 替换为 fill = Factor(..x..),您将获得所需的结果:

  ggplot(diamonds, aes(x = color, y = ..prop.., fill = factor(..x..), group = 1)) +
geom_bar() +
facet_grid(~cut)+
scale_fill_manual(values = c("red", "green", "yellow", "blue", "pink", "purple", "black")) +
theme(axis.text.x = element_text(angle=90))

enter image description here

<小时/>

或者,我总是喜欢提前进行预处理。您可以通过以下方式执行此操作:

 library(data.table)
df <- setDT(copy(diamonds))[, .(N = .N), by = .(cut, color)][, .(prop = N/sum(N), color = color), by = cut]

ggplot(data = df,
mapping = aes(x = color, y = prop, fill = color)) +
geom_col() +
facet_grid(~cut) +
scale_fill_manual(values = c("red", "green", "yellow", "blue", "pink", "purple", "black"))+
theme(axis.text.x = element_text(angle=90))

关于r - 在 ggplot 中使用 ..prop.. 时如何为条形图着色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50063362/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com