我正在尝试生成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缩放。
答案 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")