美文网首页
R可视化之美之科研绘图-11.双色条形图

R可视化之美之科研绘图-11.双色条形图

作者: 科研私家菜 | 来源:发表于2022-07-14 19:31 被阅读0次

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

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


    01 双色条形图显示

    
    library(ggplot2)
    library(RColorBrewer)
    library(Cairo)
    library(showtext)
    
    
    mydata<- read.csv("Bar_Data.csv",stringsAsFactors=FALSE)
    
    mydata$Team<-as.character(mydata$Team)
    
    
    mydata<-transform(mydata, label1=ifelse(Difference>=0, Team, NA),
                      label2=ifelse(Difference>0, NA,Team))
    
    
    mydata$Team <- factor(mydata$Team, levels = mydata$Team[order(mydata$Difference)])
    
    #CairoPDF(file="图1-8-15(a)_条形图.pdf",width=5.28,height=5.47) 
    #showtext.begin()
    ggplot(data = mydata, aes(x = Team, y = Difference,fill = Difference)) +
      geom_bar(stat = "identity", width = 0.8,colour="black",size=0.25)+
      scale_fill_gradient2(low=brewer.pal(7,"Set1")[2],mid="grey90",high=brewer.pal(7,"Set1")[1],midpoint=0)+
      geom_text(aes(y = 0,     label=label2),size=3,hjust=-0.1)+ #添加负值部分的数据标签
      geom_text(aes(y = -0.001,label=label1),size=3,hjust= 1.1)+ #添加正值部分的数据标签
      coord_flip() +   #坐标轴翻转
      ylim(-5,5)+
      theme_minimjor=element_blank(),
            panel.grid.minor=element_blank(),
            panel.grid.major.x = element_line(colour = "grey80",size=.25),
            panel.grid.minor.x = element_line(colour = "grey80",size=.25),
            plot.title=element_text(size=15,hjust=.5),
            axis.text.x = element_text(face="plain", color="black",
                                       size=11, angle=0),
            axis.text.y = element_blank(),
            legend.position="right",
            legend.text=element_text(size=10),
            legend.title=element_text(size=10))
    

    效果如下:


    02 颜色的透明度设置

    设置参数:alpha =

    library(ggplot2) # load ggplot2
    # setting seed for random numbers
    set.seed(1111)
    
    # random normal variables
    var1<-rnorm(500,-5, 1.5)
    var2<-rnorm(500, 1, 2)
    var3<-rnorm(500, -1, 3)
    
    # data frame with normal variables
    distribs = data.frame(values = c(var1, var2, var3),type = gl(n = 3, k = 500))
    
    # plot
    ggplot(data = distribs, aes(x = values, group = type)) +
      geom_density(aes(fill = type), color = "black", alpha = 0.8,size=0.5)+
      theme(legend.position = c(0.9,0.8))
    

    效果如下:



    参考资料

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

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

    相关文章

      网友评论

          本文标题:R可视化之美之科研绘图-11.双色条形图

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