其他
ggplot2绘制渐变色散点图与折线图
欢迎关注R语言学习指南
❝本节来介绍如何使用「ggplot2绘制渐变色散点图与折线图」,本文由「避尘」小伙伴投稿;小编进行了简单排版
❞
安装并加载R包
package.list=c("tidyverse","ggnewscale","viridis")
for (package in package.list) {
if (!require(package,character.only=T, quietly=T)) {
install.packages(package)
library(package, character.only=T)
}
}
导入数据
df <- read_csv("crime_immig.csv")
渐变色散点图
df %>% ggplot() +
geom_point(aes(totalpop,burg,fill=burg),color="black",shape=21, size=5)+
geom_smooth(aes(totalpop,burg,colour=burg),size=1)+
scale_fill_distiller(name="Point",palette="YlOrRd")+
theme_bw()+
theme(panel.grid=element_blank(),
legend.position = "none")
散点图添加渐变拟合曲线
df %>% ggplot() +
geom_point(aes(totalpop,burg,fill=burg),color="black",shape=21,size=5)+
geom_smooth(aes(totalpop,burg,color=..y..),size=1,fill="lightblue")+
scale_fill_distiller(name="Point",palette = "Spectral")+
scale_color_distiller(name="Point",palette = "Spectral")+
theme_bw()+
theme(panel.grid=element_blank(),legend.position = "none")
❝下面来介绍如何绘制渐变折线图
❞
加载数据
B<- read_csv("ABC.CSV")
绘制基础折线图
ggplot(B,aes(x = Year))+
geom_point(aes(y = burg,colour=burg),size=3)+
geom_line(aes(y =burg,colour=burg),size=1) +
scale_color_gradient(low = "blue", high = "red")+
theme_bw()+
theme(panel.grid=element_blank(),
legend.position = "none")
双渐变色双轴折线图
❝注意:在双折线图中,要想给另外一条折线增加不一样的渐变色,需要借助ggnewscale包的new_scale_color()才能实现
❞
ggplot(B, aes(x = Year))+
geom_point(aes(y = burg,colour=burg),size=3)+
geom_line(aes(y =burg,colour=burg),size=1) +
scale_color_gradient(low = "red", high = "blue")+
new_scale_color() + # 此处将color同时映射给了两种不同的尺度
geom_point(aes(y =(rob)/2,colour=rob),size=3)+
geom_line(aes(y =(rob)/2,colour=rob),size=1) +
scale_color_viridis()+
scale_y_continuous(name = 'burg',
sec.axis = sec_axis(~.*2,name = 'rob'))+
xlab("Year")+
theme_bw()+
theme(panel.grid = element_blank(),
legend.background = element_blank(),
legend.text = element_text(size=10),
legend.position = c(0.02,0.98),
legend.direction = "vertical",
legend.box = "horizontal",
legend.justification = c(0,1),
axis.title = element_text(size=12,face = "bold"),
axis.ticks.length = unit(-0.15, "cm"),
axis.text.x = element_text(margin = margin(t = 7),vjust = 0.4,size = 10),
axis.text.y.left = element_text(margin = margin(r = 7),size = 10),
axis.text.y.right =element_text(margin = margin(l = 7,r = 7),size=10))+
scale_x_continuous(breaks = seq(1980,2021,5))
❝下面介绍一些常用的渐变色
❞
亮丽彩虹色scale_color_gradientn(colours =rainbow(10)) 红蓝渐变scale_color_gradient(low = "blue", high = "red") 红白蓝渐变scale_color_gradient2(low = "red", mid = "white", high = "blue") 复古彩虹色scale_color_distiller(palette = "Spectral") 红黄渐变色scale_color_distiller(palette="YlOrRd") 黄绿渐变色scale_color_viridis_c() 紫黄渐变色scale_color_viridis(option = "plasma")
扫描下方二维码查看本文配套视频
数据获取
转发本文至微信群或朋友圈;公众号后台截图即可获取相关代码
学术交流群
❝目前已有2千多位小伙伴已经加入交流群,期待您的加入
❞
「关注下方公众号下回更新不迷路」,如需要加入微信交流群,请在菜单栏处添加作者微信,备注单位+方向+姓名即可邀您进群
跟着PNAS学绘图-ggplot2绘制散点图添加渐变拟合曲线
2021年个人年度小总结
新手友好:5分生信SCI全文复现
ggplot2优雅的绘制点图
[热图-华夫图-瀑布图]用ggplot2一次性解决
ggplot2绘制基因作用元件图