【问题标题】:Stacked multivariate Bar charts having percentage inside the bars条形内有百分比的堆叠多元条形图
【发布时间】:2018-12-09 06:00:25
【问题描述】:

我有以下数据:

loan_amnt   term      grade sub_grade home_ownership  verification_status  d_status
7000        60 months C     C5        RENT            Not Verified         Not Defaulted
6500        60 months C     C3        OWN             Not Verified         Not Defaulted
12000       36 months B     B5        OWN             Verified             Defaulted
9000        36 months C     C1        RENT            Verified             Not Defaulted
1000        36 months D     D1        RENT            Not Verified         Defaulted

我需要多元条形图,我希望在其中填充d_status,并且 y 轴具有百分比值。在 x 轴上,我想要 termgradeverification_status。这意味着我将需要 3 个堆叠的条形图。

如何使用 ggplot 进行绘图?请帮忙。

【问题讨论】:

  • 所以我对你的问题投了反对票,因为它没有表现出任何努力,而且你忘了说,“请”(故意的双关语)。没有“免费午餐”。好的,事情就是这样,你想要答案,然后你必须表现出一些努力。你都尝试了些什么?数据是什么样的,变量的类型是什么等。请参阅此处了解如何创建minimum reproducible example

标签: r ggplot2 bar-chart


【解决方案1】:

您可以使用gridExtra 库。

df <- read.table(text = "loan_amnt   term      grade sub_grade home_ownership  verification_status  d_status
7000        60_months C     C5        RENT            Not_Verified         Not_Defaulted
6500        60_months C     C3        OWN             Not_Verified         Not_Defaulted
12000       36_months B     B5        OWN             Verified             Defaulted
9000        36_months C     C1        RENT            Verified             Not_Defaulted
1000        36_months D     D1        RENT            Not_Verified         Defaulted", 
                 header = TRUE)

library(ggplot2)
library(scales)
g1 <- ggplot(df, aes(x = term, fill = d_status)) +
  geom_bar(aes(y = (..count..)/sum(..count..))) + 
  scale_y_continuous(labels = percent) + 
  ylab("") +
  theme(strip.text.x = element_blank(),
      legend.position=c(0.85, 0.9))

g2 <- ggplot(df, aes(x = grade, fill = d_status)) +
  geom_bar(aes(y = (..count..)/sum(..count..))) + 
  scale_y_continuous(labels = percent) + 
  ylab("")  +
  theme(strip.text.x = element_blank(),
        legend.position=c(0.85, 0.9))


g3 <- ggplot(df, aes(x = verification_status, fill = d_status)) +
  geom_bar(aes(y = (..count..)/sum(..count..))) + 
  scale_y_continuous(labels = percent) + 
  ylab("") +
  theme(strip.text.x = element_blank(),
        legend.position=c(0.85, 0.9))


library(gridExtra)
grid.arrange(g1, g2, g3, nrow = 1)

结果是:

【讨论】:

    猜你喜欢
    • 2016-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-24
    • 1970-01-01
    • 2021-05-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多