ggplot2當我在條形圖 ( geom_bar()) 中同時包含填充和組引數時,R 的庫似乎存在問題。我已經嘗試了幾個小時尋找答案,但找不到可以提供幫助的答案。這實際上是我在這里的第一篇文章。
為了提供一點背景知識,我有一個名為smokement(煙霧和心理健康的縮寫)的資料框,一個名為smoke100(在過去 100 天內吸煙?)的分類變數,帶有“是”和“否”,以及另一個名為(吸煙misnervs頻率)的分類變數緊張感)有 5 個可能的值:“全部”、“大部分”、“一些”、“一點”和“無”。
當我運行此代碼時,我得到以下結果:
ggplot(data = smokement)
geom_bar(aes(x = smoke100, fill = smoke100))
facet_wrap(~misnervs, nrow = 1)

但是,我想要的結果是讓所有分組的條形圖顯示它們各自的比例。通過讀取位的“R資料科學”的書,我發現我需要包括y = ..prop..并group = 1在aes()實作它:
ggplot(data = smokement)
geom_bar(aes(x = smoke100, y = ..prop.., group = 1))
facet_wrap(~misnervs, nrow = 1)

最后,我嘗試使用fill = smoke100引數 inaes()以顏色顯示這個分類變數,就像我在第一個代碼中所做的那樣。但是當我添加這個填充引數時,它不起作用!代碼運行,但它顯示與第二個代碼完全相同的輸出,好像這次填充引數以某種方式被忽略了!
ggplot(data = smokement)
geom_bar(aes(x = smoke100, y = ..prop.., group = 1, fill = smoke100))
facet_wrap(~misnervs, nrow = 1)

Does anyone have an idea of why this happens, and how to solve it? My end goal is to display each value of smoke100 (the "Yes" and "No" bars) with colors and a legend at the right, just like on the first graph, while having each grouping level of "misnervs" display their respective proportions of smoke100 ("Yes", "No") levels, just like on the second graph.
EDIT:
> dim(smokement)
[1] 35471 6
> str(smokement)
'data.frame': 35471 obs. of 6 variables:
$ smoke100: Factor w/ 2 levels "Yes","No": 1 2 1 2 1 1 1 1 1 1 ...
$ misnervs: Factor w/ 5 levels "All","Most","Some",..: 3 4 5 4 1 5 3 3 5 5 ...
$ mishopls: Factor w/ 5 levels "All","Most","Some",..: 3 5 5 5 5 5 5 5 5 5 ...
$ misrstls: Factor w/ 5 levels "All","Most","Some",..: 3 5 5 3 1 5 3 5 1 5 ...
$ misdeprd: Factor w/ 5 levels "All","Most","Some",..: 5 5 5 5 4 5 5 5 5 5 ...
$ miswtles: Factor w/ 5 levels "All","Most","Some",..: 5 5 5 5 5 5 5 5 5 5 ...
> head(smokement)
smoke100 misnervs mishopls misrstls misdeprd miswtles
1 Yes Some Some Some None None
2 No A little None None None None
3 Yes None None None None None
4 No A little None Some None None
5 Yes All None All A little None
6 Yes None None None None None
As for the output without group = 1
ggplot(data = smokement)
geom_bar(aes(x = smoke100, y = ..prop.., fill = smoke100))
facet_wrap(~misnervs, nrow = 1)

uj5u.com熱心網友回復:
除了
注意從geom_barto的切換geom_col:geom_bar使用行計數,geom_col使用資料中的值。
作為一個粗略和準備好的 QC,這里是生成“全灰色”圖的代碼的等價物:
diamonds %>%
ggplot()
geom_bar(aes(x=color, y=..prop.., fill=color, group=1))
facet_wrap(~cut)

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