R语言 以相对于X轴中月份的百分比标记的条形图

avwztpqn  于 2023-02-26  发布在  其他
关注(0)|答案(1)|浏览(101)

我有这样一个数据框:

df <- data.frame(
     month = month.name[1:6],
     shirts = runif(6, min=1000, max=2000),
     hats = runif(6, min=1000, max=2000)
    ) |>
    pivot_longer(cols=c("shirts", "hats"), names_to="category", values_to="income")

df

数据框:

# A tibble: 12 × 3
   month    category income
   <chr>    <chr>     <dbl>
 1 January  shirts    1782.
 2 January  hats      1489.
 3 February shirts    1094.
 4 February hats      1954.
 5 March    shirts    1467.
 6 March    hats      1483.
 7 April    shirts    1512.
 8 April    hats      1890.
 9 May      shirts    1600.
10 May      hats      1914.
11 June     shirts    1333.
12 June     hats      1609.

为了绘制一个条形图,显示每个月每个类别的相对收入百分比,我这样做了:

df |> 
    group_by(month, category) |>
    summarize(income = sum(income, na.rm=TRUE)) |>
    ggplot(aes(x=month,y=income, fill=category)) +
    geom_bar(position="dodge", stat="identity") + 
    geom_text(aes(label=paste0(percent(income/sum(income)))), position = position_dodge(width=0.9), angle = 90, hjust=-0.1) +
    labs(x="Month",y="Income") +
    ylim(0, 4000)

但它正在计算percentage relative to the total income sum from january to june
我想这个百分比是相对于每个月的总收入总和。
我可以改变什么或添加一些新的情节代码,以实现这一点?

esyap4oy

esyap4oy1#

要使用每月总计作为分母,您需要在按month分组时计算百分比。在summarize()之后,数据仍按month分组,因此在此处添加mutate()

library(dplyr)
library(ggplot2)
library(scales)

df |> 
    group_by(month, category) |>
    summarize(income = sum(income, na.rm=TRUE)) |>
    mutate(pct_label = percent(income/sum(income), accuracy = 0.1)) |>
    ungroup() |>
    ggplot(aes(x=month,y=income, fill=category)) +
    geom_col(position="dodge") + 
    geom_text(aes(label = pct_label), position = position_dodge(width=0.9), angle = 90, hjust=-0.1) +
    labs(x="Month",y="Income") +
    ylim(0, 4000)

另请注意,geom_col()等效于geom_bar(stat = "identity")

相关问题