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

时间:2018-04-27 13:21:21

标签: r ggplot2 bar-chart

我正在尝试在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)

1 个答案:

答案 0 :(得分:1)

如果您将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))