R - 缩放/乘以geom_bar计算另一个变量

时间:2018-04-19 02:29:02

标签: r ggplot2

我正在尝试生成geom_bar美国不同州的贷款计数表。要做到这一点,我正在使用

ggplot(aes(x = BorrowerState), data = loans) + geom_bar()

其中loans是数据框。但是,我想根据每个州的人口来计算这些数量,以计算人均y轴数。我有另一个名为state_pops的数据框,其中包含州名和人口的列,但我不知道如何使ggplot按照州的人口的倒数来计算计数 - 各州的基础。请帮忙吗?

更新:根据评论,我意识到我应该为此包含样本数据。抱歉!这里有一些模拟数据,以及建议加入将州人口纳入主loans数据框:

library(dplyr)

loans <- data.frame("BorrowerState" = c("CO", "CO", "GA", "GA", "MN"),
                          "extraColumn" = c("a", "b", "c", "d", "e"))

state_pops <- data.frame("State" = c("GA", "MN", "CO", "CA"),
                         "Population" = c(1000, 2000, 3000, 4000))

loans <- left_join(loan_states, state_pops, by = c("BorrowerState" = "State"))

不幸的是,我仍然没有看到如何制作一个条形图,其数量按1 / Population_value缩放。

1 个答案:

答案 0 :(得分:0)

我认为以下内容符合您的要求(请注意,我在loan_states的调用中将loans更改为left_join,因为之前您称之为数据框的是{) :

library(ggplot2)
library(dplyr)

loans <- data.frame("BorrowerState" = c("CO", "CO", "GA", "GA", "MN"),
                    "extraColumn" = c("a", "b", "c", "d", "e"))
state_pops <- data.frame("State" = c("GA", "MN", "CO", "CA"),
                         "Population" = c(1000, 2000, 3000, 4000))
loans <- left_join(loans, state_pops, by = c("BorrowerState" = "State"))

ggplot(loans) +
  geom_col(aes(x=BorrowerState, y=1/Population)) +
  ylab("Loan Fraction")

enter image description here