一个月的备考终于结束了,公号的推文也会陆续进行原创推文制作,也希望大家继续支持哦!本期推文就介绍一篇关于使用ggplot2 绘制带有颜色映射的相关性散点图,本期涉及的知识点如下:
这里大部分和推文R-ggplot2 学术散点图绘制 中的绘图技巧一样,下面我直接给出代码,如下:
#绘图 + 颜色
library(tidyverse)
library(RColorBrewer)
library(ggthemes)
palette<-brewer.pal(11,"Spectral")
plot2 <- ggplot(data = scatter_data,aes(x = true_data,y = model01_estimated)) +
stat_bin_2d(binwidth = c(.012,.012))+
scale_fill_gradientn(colours = rev(palette),limits=c(0,40), breaks=c(0,10,20,30,40),
labels=c("0","10",'20','30','>40'))+
#绘制拟合线并设置为红色
geom_smooth(method = 'lm',se = F,color='red',size=1)+
#绘制对角线
geom_abline(slope = 1,intercept = 0,color='black',linetype = "dashed",size=1) +
scale_x_continuous(limits = c(-.1,2),expand = c(0,0))+
scale_y_continuous(limits = c(-.1,2),expand = c(0,0))+
guides(fill = guide_colorbar(title = "Counts", title.position = "top",title.hjust = .5,ticks = T))+
labs(x ='True Values',y="Model Estimated Value",
title = "The scatter chart of Train data and Tset data",
subtitle = "scatter R-ggplot2 Exercise",
caption = 'Visualization by DataCharm')+
#theme_classic()+
theme(text = element_text(family = "Times_New_Roman",face='bold'),
axis.text = element_text(family = 'Times_New_Roman',size = 12,face = 'bold'),
#修改刻度线内
axis.ticks.length=unit(-0.22, "cm"),
#加宽图边框
#panel.border = element_rect(size=1),
axis.line = element_line(size = .8),
axis.ticks = element_line(size = .8),
#去除图例标题
#legend.title = element_blank(),
#设置刻度label的边距
axis.text.x = element_text(margin=unit(c(0.5,0.5,0.5,0.5), "cm")),
axis.text.y = element_text(margin=unit(c(0.5,0.5,0.5,0.5), "cm")))
plot2
最终,得到的可视化结果如下:
这里提一下,由于绘制的数据较少,可能导致绘制的结果不太美观,当然,在数据足够多的情况下,你也可以绘制出如下的相关性散点图:
(图中colorbar的位置、字体都是可以自由设置的啊)
使用R-ggplot2绘制学术图表确实可以避免Python-matplotlib需要自定义设置问题,提高绘图效率。大家在绘制图表时,可以根据而自己喜好自由选取喜欢的绘图工具啊。