我確定我在這里遺漏了一些明顯的東西,但是已經嘗試了一百萬次不同的迭代,但似乎找不到正確的食譜。我正在處理調查資料并在 facet_grid 中對其進行分面,現在效果很好:
# ingest some data
df <- structure(list(Q52_bin = structure(c(3L, 2L, 2L, 2L, 2L, 2L), .Label = c("low",
"medium", "high"), class = "factor"), Q53_bin = structure(c(2L,
3L, 2L, 2L, 2L, 2L), .Label = c("low", "medium", "high"), class = "factor"),
Q57_bin = structure(c(2L, 2L, 2L, 2L, 2L, 2L), .Label = c("low",
"medium", "high"), class = "factor"), Q4 = c("A little",
"Some", "Some", "A great deal", "A lot", "Some")), row.names = c(NA,
-6L), class = c("tbl_df", "tbl", "data.frame"))
# make column names coherent and simplified
names(df) <- c("Q52_bin", "Q53_bin", "Q57_bin", "response")
df %>%
pivot_longer(!response, names_to = "bin_name", values_to = "b") %>%
count(response, bin_name, b) %>%
ggplot(aes(x=n,y=response))
geom_col(position="stack", stat="identity")
scale_fill_discrete()
facet_grid(vars(b), vars(bin_name)) labs(caption = "How much have you thought about climate change before today?", x = "", y = "")
但是,我真正想要的是這些條是堆疊的水平條,每個方面內有一個條,使用顏色表示不同的李克特反應。我在想我可以簡單地切換到:
ggplot(aes(x=n,fill=response))
geom_bar(position="fill")
但輸出是不連貫的(無數條窄條)。關于如何根據需要切換它的任何建議?
uj5u.com熱心網友回復:
不確定我是否理解您的問題,但我認為這就是您所追求的。
示例代碼:
df %>%
pivot_longer(!response, names_to = "bin_name", values_to = "b") %>%
count(response, bin_name, b) %>%
ggplot(aes(x=n,y=b, fill=response))
geom_bar(position="stack", stat="identity")
scale_fill_discrete()
facet_grid(vars(b), vars(bin_name))
labs(caption = "How much have you thought about climate change before today?", x = "", y = "")
陰謀:

如果改變
facet_grid(~b) # b takes values medium and high
response bin_name b n
<chr> <chr> <fct> <int>
1 A great deal Q52_bin medium 1
2 A great deal Q53_bin medium 1
3 A great deal Q57_bin medium 1
4 A little Q52_bin high 1
5 A little Q53_bin medium 1
6 A little Q57_bin medium 1
7 A lot Q52_bin medium 1
8 A lot Q53_bin medium 1
9 A lot Q57_bin medium 1
10 Some Q52_bin medium 3
11 Some Q53_bin medium 2
12 Some Q53_bin high 1
13 Some Q57_bin medium 3
如果你想忽略 Q52_bin...-s

為了更好地使用不同的主題
library(ggtheme)
theme_gdocs()

轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/443271.html
