簡體   English   中英

如何使用 ggplot2 在直方圖中 plot 變量的份額

[英]How to plot the share of a variable in a histogram with ggplot2

我試過查看舊線程沒有成功。 我正在嘗試 plot 直方圖中不同議會會議中男性立法者的份額。

這是我的代碼,它有效,但顯示了立法者的數量(不是份額)。 我怎樣才能 plot 共享? 謝謝!

    mergedf %>%
ggplot( aes(x = session, fill = factor(sex))) +
    geom_histogram (binwidth = 0.5)+
theme_minimal()+
  theme(legend.position ="bottom")+
  labs(title = "Share of male legislators by session", x= "Session", y = "Share of legislators", 
       fill ="sex")

編輯:我通過這張表獲得了立法者的份額,但我不知道如何將它整合到直方圖中。

mergedf %>% 
  tabyl (session, sex) %>% 
  adorn_percentages() %>% 
  adorn_pct_formatting ()

一種選擇是使用一些dplyr動詞來計算計數和百分比,然后可以通過geom_col顯示為條形圖(直方圖是不同的),如下所示:

mergedf <- data.frame(
  sessions = c( 1, 2, 3, 4, 5, 2, 3, 4, 2),
  sex = c ("female", "female", "female", "male", "female", "female", "female", "male", "male")
)

library(dplyr)
library(ggplot2)

mergedf %>%
  group_by(sessions, sex) %>% 
  summarise(n = n()) %>%
  mutate(pct = n / sum(n)) %>%
  ggplot( aes(x = factor(sessions), y = pct, fill = sex)) +
  geom_col(width = .6)+
  theme_minimal()+
  theme(legend.position ="bottom")+
  labs(title = "Share of male legislators by session", x= "Session", y = "Share of legislators", 
       fill ="sex")
#> `summarise()` has grouped output by 'sessions'. You can override using the
#> `.groups` argument.

您只需在geom_histogram參數中指定position="fill"

library(ggplot2)
mergedf <- data.frame(
  session = c( 1, 2, 3, 4, 5, 2, 3, 4, 2),
  sex = c ("female", "female", "female", "male", "female", "female", "female", "male", "male")
)

ggplot(mergedf, aes(x = session, fill = factor(sex))) +
  geom_histogram (binwidth = 0.5, position = "fill") +  # <- HERE
  theme_minimal() +
  theme(legend.position ="bottom") +
  labs(title = "Share of male legislators by session", 
       x= "Session", y = "Share of legislators", fill ="sex")

從技術上講,您並沒有真正構建直方圖(計數的合並分布),而是條形圖,因此您也可以使用geom_bar ,格式相同:

ggplot(mergedf, aes(x = session, fill = factor(sex))) +
  geom_bar(position="fill") +
  theme_minimal () +
  theme(legend.position ="bottom") +
  labs(title = "Share of male legislators by session", 
       x= "Session", y = "Share of legislators", fill ="sex")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM