简体   繁体   English

具有动态返回值的 Ggplot scale_fill_manual

[英]Ggplot scale_fill_manual with dynamic returned values

I have a dataframe with multiple columns of factor type (with 5 levels: Dark Green, Green, Orange, Yellow, Grey) although each contains different values as per the screenshot below.我有一个 dataframe,其中包含多列因子类型(有 5 个级别:深绿色、绿色、橙色、黄色、灰色),尽管每个包含不同的值,如下面的屏幕截图所示。

在此处输入图像描述

I tried to define a function to make a bar chart with colors of the legend manually set by the values contained in the selected column like so我试图定义一个 function 来制作一个条形图,其中包含由所选列中包含的值手动设置的图例 colors,如下所示

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

My question is: how can I set the parameters values and labels dynamically depending on the column provided to the function make_graph ?我的问题是:如何根据提供给 function make_graph的列动态设置参数valueslabels For example, if I do this make_graph(df, 'col_2') it will display a graph of 3 bars with colors dark green, green and orange and values of legend are 'great', 'good' and 'ok'例如,如果我执行此make_graph(df, 'col_2')它将显示 3 个条形图,其中 colors 为深绿色、绿色和橙色,图例值为“很好”、“好”和“好”

PS: below is the result of the code provided by akrun where the legend values were not aligned with the colors (for example darkgreen should be labelled as 'great' instead of 'terrible') PS:以下是 akrun 提供的代码的结果,其中图例值与 colors 不一致(例如,深绿色应标记为“好”而不是“可怕”)

在此处输入图像描述

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)



}

-testing -测试

make_graph(df1, "col_2")

data数据

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"))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM