[英]Ggplot scale_fill_manual with dynamic returned values
我有一個 dataframe,其中包含多列因子類型(有 5 個級別:深綠色、綠色、橙色、黃色、灰色),盡管每個包含不同的值,如下面的屏幕截圖所示。
我試圖定義一個 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
我的問題是:如何根據提供給 function make_graph
的列動態設置參數values
和labels
? 例如,如果我執行此make_graph(df, 'col_2')
它將顯示 3 個條形圖,其中 colors 為深綠色、綠色和橙色,圖例值為“很好”、“好”和“好”
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)
}
-測試
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"))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.