美文网首页
R可视化之美之科研绘图-23.块状直方图

R可视化之美之科研绘图-23.块状直方图

作者: 科研私家菜 | 来源:发表于2022-08-28 14:46 被阅读0次

本内容为【科研私家菜】R可视化之美之科研绘图系列课程

快来收藏关注【科研私家菜】


01 方形块状直方图

library(ggplot2)
library(RColorBrewer)
library(scales)

x <- rnorm(250 , mean=10 , sd=1) #(a2) ??????̬?ֲ???ԭʼ????

#x <-sample(1:20, 250, replace = TRUE) #(a1) ???Ӿ??ȷֲ???ԭʼ????

step<-0.2
breaks<- seq(min(x)-step,max(x)+step,step)#"sturges"

hg <- hist(x, breaks = breaks , plot = FALSE) # Make histogram data but do not plot

bins <- length(hg$counts) # How many bin categories are needed?
yvals <- numeric(0)                  # A blank variable to fill in
xvals <- numeric(0) 
for(i in 1:bins) {                  # Start a loop
  yvals <- c(yvals, hg$counts[i]:0)  # Work out the y-values
  xvals <- c(xvals, rep(hg$mids[i], hg$counts[i]+1))  # Work out x-values
}    # End the loop
                                                   # End the loop
dat <- data.frame(xvals, yvals)  # Make data frame of x, y variables
dat <- dat[yvals > 0, ]          # Knock out any zero y-values

colormap <- colorRampPalette(rev(brewer.pal(11,'Spectral')))(32)

ggplot(dat, aes(x=xvals,y=yvals,fill=yvals))+
  geom_tile(colour="black")+
  scale_fill_gradientn(colours=colormap)+
  ylim (0, max(yvals)*1.3)+
  theme(
    text=element_text(size=15,color="black"),
    plot.title=element_text(size=15,family="myfont",face="bold.italic",hjust=.5,color="black"),
    legend.background = element_blank(),
    legend.position=c(0.9,0.75)
  )

效果如下:


02 圆形块状直方图

ggplot(dat, aes(x=xvals,y=yvals,fill=yvals))+
  geom_point(colour="black",shape=21,size=4)+
  scale_fill_gradientn(colours=colormap)+
  ylim (0, max(yvals)*1.3)+
  theme(
    text=element_text(size=15,color="black"),
    plot.title=element_text(size=15,family="myfont",face="bold.italic",hjust=.5,color="black"),
    legend.background = element_blank(),
    legend.position=c(0.9,0.75)
  )

效果如下:



参考资料

《R语言数据可视化之美》

关注R小盐,关注科研私家菜(溦❤工众號: SciPrivate),有问题请联系R小盐。让我们一起来学习 R可视化之美之科研绘图

相关文章

网友评论

      本文标题:R可视化之美之科研绘图-23.块状直方图

      本文链接:https://www.haomeiwen.com/subject/jeslwrtx.html