R语言 Ggplot scale_fill_manual,带有动态返回值

3duebb1j  于 2023-01-28  发布在  其他
关注(0)|答案(1)|浏览(124)

我有一个 Dataframe ,其中包含多个因子类型的列(5个级别:深绿色、绿色、橙色、黄色、灰色),但根据下面的屏幕截图,每种颜色包含不同的值。

我尝试定义一个函数来制作一个条形图,其中图例的颜色由所选列中包含的值手动设置,如下所示

library(tidyverse)
make_graph <- function(df, col){
  data = select(df, group, col)
  G = data$group
  C = data$col
  tbl = prop.table(table(G, C))
  DF = data.frame(tbl) %>% filter(freq != 0)
ggplot(data, aes(x=G,y=Freq, fill=C)) +
 geom_bar(stat="identity", position="dodge") + theme_minimal() +
 scale_fill_manual(values=c(?????), labels=c(?????))  # needs to be automatically filled with the values contained in the selected column

我的问题是:如何根据提供给函数make_graph的列动态设置参数valueslabels?例如,如果我执行make_graph(df, 'col_2'),它将显示一个包含3个条形的图形,颜色分别为深绿色、绿色和橙色,图例值分别为"great"、"good"和"ok"
PS:以下是akrun提供的代码的结果,其中图例值与颜色不一致(例如,深绿色应标记为"伟大"而不是"可怕")

laik7k3q

laik7k3q1#

library(dplyr)
library(ggplot2)
make_graph <- function(df, col){
 keyval <- setNames(c("great", "good", "ok", "poor", "terrible"), 
      c("dark green", "green", "orange", "yellow", "grey"))
 fill_m <- keyval[df[[col]]]
df %>%
   select(group, all_of(col)) %>%
   count(across(everything())) %>%
   mutate(prop = n/sum(n)) %>%
   filter(n != 0) %>%
   ggplot(aes(x = group, y = n, fill = .data[[col]])) +
     geom_bar(stat= "identity", position = "dodge") + 
     theme_minimal() +
     scale_fill_manual(values = names(fill_m), labels = fill_m)


}
  • 测试
make_graph(df1, "col_2")

数据

df1 <- structure(list(group = structure(c(1L, 2L, 1L, 2L), levels = c("1", 
"2"), class = "factor"), col_1 = c("dark green", "dark green", 
"dark green", "dark green"), col_2 = c("dark green", "green", 
"orange", "orange"), col_3 = c("green", "yellow", "dark green", 
"grey"), col_4 = c("grey", "dark green", "orange", "yellow"), 
    col_5 = c("dark green", "grey", "grey", "grey")), row.names = c(NA, 
-4L), class = c("tbl_df", "tbl", "data.frame"))

相关问题