你好,我想创建一个显示条形和线条的 ggplot。 理想情况下,我希望条形图显示“cyl”变量,y 轴显示 SumHp。 此外,在辅助 y 轴上我想绘制一条线(使用 df2 数据集)。
总而言之,一行使用 df2(年份显示在线上方)和 3 个条形图(“cyl”变量为 4,6,8)
data("mtcars")
#Generate Random Years from 2016-2019
mtcars$Year <- mtcars$Acc_Year <- round(runif(nrow(mtcars),2016,2019))
#Find the sum of "hp" and mean of "wt" for each category in "cyl"
df1 <- as.data.frame(mtcars %>% group_by(cyl) %>% summarise(SumHp = sum(hp),
MeanWt = mean(wt)))
#Find average "wt" for each Year
df2 <- as.data.frame(mtcars %>% group_by(Year) %>% summarise(MeanWtYear = mean(wt)))
coeff <- 60
ggplot(df1, aes(x = cyl, weights = SumHp)) + geom_bar() +
geom_line(data = df2, aes(x = Year, y = MeanWtYear), color="blue") +
scale_y_continuous(
# Features of the first axis
name = "First Axis",
# Add a second axis and specify its features
sec.axis = sec_axis(~.*coeff, name="Second Axis")
)