❝本节来随意绘制一张组合图,数据为R内置数据,图表无实际意义,整个过程仅参考。希望对各位观众老爷能有所帮助。「代码会整合上传到学习交流群」,购买过小编R数据可视化文档的朋友可在所加的交流群内获取下载,有需要的朋友可关注文中介绍加入交流群。 ❞
library(tidyverse)
library(gapminder)
library(cowplot)
df1 <- gapminder %>% filter(continent!="Africa") %>%
select(2,year,gdpPercap) %>%
group_by(year) %>%
summarise(word = sum(gdpPercap))
df2 <- gapminder %>% filter(continent=="Africa") %>%
select(year,gdpPercap) %>%
group_by(year) %>%
summarise(Africa = sum(gdpPercap)) %>%
mutate(type="Africa",
year=as.character(year))
p1 <- ggplot(data=df1,aes(year,word))+
geom_line(group=1,size=3,color="#7294D4")+
scale_x_continuous(expand =expansion(mult = c(0,0.01)),
breaks = df1 %>% filter(year %in% c(1952,1962,1972,1982,1992,2002,2007)) %>%
pull(year),
labels = df1 %>% filter(year %in% c(1952,1962,1972,1982,1992,2002,2007)) %>%
pull(year))+
labs(x=NULL,y=NULL)+
theme(plot.background = element_blank(),
panel.background = element_blank(),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
plot.margin = unit(c(0.5,1,0.5,0.5), unit="cm"),
axis.line.x = element_line(size=2,color="#7294D4"),
axis.text.x=element_text(angle =0,color="black",vjust=0.5),
axis.ticks.length.x = unit(0.3,"cm"))
p2 <- ggplot(data=df2,aes(year,Africa))+
geom_col(aes(fill=type),show.legend = F)+
scale_y_continuous(position = "right",expand =expansion(mult = c(0,0)))+
scale_x_discrete(expand =expansion(mult = c(0,0)),
breaks = df1 %>% filter(year %in% c(1952,1962,1972,1982,1992,2002,2007)) %>%
pull(year),
labels = df1 %>% filter(year %in% c(1952,1962,1972,1982,1992,2002,2007)) %>%
pull(year))+
scale_fill_manual(values=c("#C6CDF7"))+
labs(x=NULL,y=NULL)+
theme(plot.background = element_blank(),
panel.background = element_blank(),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
axis.line.x = element_line(color="grey"),
axis.text.x=element_text(angle = 45,color="black",vjust=1,hjust=1))
# 拼图
plot <- ggdraw(p1)+
draw_plot(p2,x =0.4, y = 0.07,width = 0.6, height = 0.5,scale = 0.95)+
draw_line(x=c(0.13,0.43),y=c(0.09,0.17),linetype=2)+
draw_line(x=c(0.89,0.93),y=c(0.157,0.08),linetype=2)
ggsave(plot,file="barplot.pdf",dpi=300,width =5.69,height=4.98,unit="in")
❝本节介绍到此结束,有需要学习R数据可视化的读者,欢迎购买小编的R数据可视化案例文档,「购买将自动获得2024年度更新的绘图文档代码,无需在付费」。目前此文档(2023+2024)「已经更新上传了150+案例文档」,每个案例都附有相应的数据和代码,并配有对应的注释文档,方便大家学习和参考。可到小编的「淘宝店铺-R语言数据分析指南」下单购买。 ❞
「2024更新的绘图内容同时包含数据+代码+markdown注释文档+文档清单」
注:2022版与2023版文档为单独售卖,买任意一年的都可获取2024的文档,「小编只分享案例文档不额外回答问题。」