我正在尝试创建两个 y 轴图。当我单独绘制条形图和线图时,它们似乎工作正常,但我很难将两者结合起来。
对于我的条形图,这是我的数据示例
治疗 | 月 | 水果起源 | 平均体重 |
---|---|---|---|
F400 | 4 | 1 | 33.669 |
F400 | 4 | 2 | 26.200 |
这是我的情节本身的代码:
f400plot_fw <- ggplot(data= f400weight, aes(x = factor(month), y = avg_weight, fill = factor(fruit_origin) , color = factor(fruit_origin))) +
geom_bar(stat = "identity", position = "dodge", alpha = 0.7) +
labs(x="", y="Aplot verage Fruit Weight (g)") +
geom_errorbar(aes(ymin = avg_weight - error, ymax = avg_weight + error), position = position_dodge(0.9), width = 0.25, show.legend = FALSE) +
theme_bw()+
theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(), legend.position = "none", axis.title.y = element_text(size=9), axis.text = element_text(size = 8)) + ylim(0,50) +
scale_fill_discrete(name = "Fruit Origin") + scale_color_discrete(name = "Fruit Origin") +
scale_fill_manual(values=c('deepskyblue1','forestgreen', 'navyblue', 'blueviolet')) + scale_color_manual(values=c('grey4', 'grey4', 'grey4', 'grey4'))
然后类似地,对于我的线图,该图的数据和代码如下所示
治疗 | 月 | 产量 |
---|---|---|
F400 | 4 | 0.11 |
F400 | 5 | 2.02 |
lineup <- ggplot(data=montgomery, aes(x = month, y = yieldypoo, group =1)) +
geom_line(size=0.5) +
labs(x="Month of Production", y="Total Weekly Yield (kg)") +
theme_bw()+
theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank())
lineup
当我将两者结合起来时,这就是我编写的代码,第三张图片就是我得到的
ggplot() + geom_col(data= f400weight, aes(x = factor(month), y = avg_weight, fill = factor(fruit_origin) , color = factor(fruit_origin)), position = "dodge", alpha = 0.7) +
labs(x="Month of Production", y="Average Fruit Weight (g)") +
theme_bw()+
theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank()) +
scale_fill_discrete(name = "Fruit Origin") + scale_color_discrete(name = "Fruit Origin") +
scale_fill_manual(values=c('deepskyblue1','forestgreen', 'navyblue', 'blueviolet')) + scale_color_manual(values=c('grey4', 'grey4', 'grey4', 'grey4')) +
geom_line(data = montgomery, aes(x = month, y = yield), size = 0.5, group =1) +
scale_y_continuous(sec.axis = sec_axis(~.*0.2, name = "Total Weekly Yield (kg)"))