R语言 次轴(百分比ggplot2)

zujrkrfu  于 2022-12-25  发布在  其他
关注(0)|答案(1)|浏览(214)

有人能帮我添加次轴的百分比吗?我尝试了不同的方法,但没有得到任何结果。
我将提供以下数据:

year <- c("2010","2011","2012","2013","2014","2015","2016","2017","2018","2019","2020","2010","2011","2012","2013","2014","2015","2016","2017","2018","2019","2020")
sex <- c("male","male","male","male","male","male","male","male","male","male","male","female","female","female","female","female","female","female","female","female","female","female")
number <- c(12,5,15,5,4,6,5,5,8,4,0,54,64,70,50,54,35,40,37,42,36,24)
perFailed <- c(0.090909091,0.057971014,0.117647059,0.163636364,0.068965517,0.048780488,0.044444444,0.071428571, 0.1,0.1,0)
data <- data.frame(year,sex,number,perFailed)
data$year <- as.factor(data$year)
library(ggplot2)
ggplot(data=data, aes(x=year, y=number, fill=sex)) +
  geom_bar(stat="identity", position=position_dodge()) +
  theme_bw()

我不知道是怎么做到的,但是R复制了我的上一列(perFailed),这个数据需要在辅助轴上绘制为geom_line()
谢谢大家。

qhhrdooz

qhhrdooz1#

试试这个:

ratio <- max(data$number) / max(data$perFailed)
data <- transform(data, perFailedScaled = perFailed * ratio)
head(data)
#   year  sex number  perFailed Year perFailedScaled
# 1 2010 male     12 0.09090909 2010        38.88889
# 2 2011 male      5 0.05797101 2011        24.79871
# 3 2012 male     15 0.11764706 2012        50.32680
# 4 2013 male      5 0.16363636 2013        70.00000
# 5 2014 male      4 0.06896552 2014        29.50192
# 6 2015 male      6 0.04878049 2015        20.86721

ggplot(data=data, aes(x=year, y=number, fill=sex)) +
  geom_bar(stat="identity", position=position_dodge()) +
  geom_line(aes(x = match(year, sort(unique(year))), y = perFailedScaled), 
            data = ~ subset(., sex == "male")) +
  scale_y_continuous(sec.axis = sec_axis(~ . / ratio, labels = scales::label_percent())) +
  theme_bw()

注:
1.我假设,既然数字在"male""female"之间是不变的,那么将数据减少到其中一个是可以的,如果不减少,这行就会被重复打印,虽然这很少有影响,甚至不会被注意到,但似乎是不必要的。
1.使用match(year, sort(unique(year)))有点像黑客。叠加轴可能会有点问题,这是一种有效的方法。

相关问题