在R中画出各班的百分比与各班所含的总金额的比较。

问题描述 投票:0回答:1

我是R编程的新手,我有一个问题,要显示每个班级的百分比与所有班级的总账单比较。例如,我有数据。

dat <- data.frame(
    time = factor(c("Breakfast","Lunch","Dinner"), levels=c("Breakfast","Lunch","Dinner")),
    total_bill = c(12.75,14.89, 17.23)
)

我想用 ggplotgeom_bar 显示百分比是这样的:对于类早餐的百分比是12.75(12.75+14.89+17.23).对于午餐和晚餐,我想同样的.任何帮助将是非常感激的。

ggplot2 geom-bar
1个回答
0
投票

最直接的解决方案是对你的数据做一些预处理,使绘图更容易。 有一些方法可以做到这一点,与 ggplot但老实说,这是我处理这个问题的方式。

# add a column for percent of total bill
dat$bill.perc <- (dat$total_bill/sum(dat$total_bill)) * 100

# example plot with some minimal formatting
ggplot(dat, aes(time, bill.perc)) +
    geom_col(width=0.7, aes(fill=time), show.legend = FALSE) +
    theme_bw()

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.