美文网首页R语言做图R可视化小本本
【R>>ggplot2】坐标轴刻度位置调整

【R>>ggplot2】坐标轴刻度位置调整

作者: 高大石头 | 来源:发表于2021-07-26 00:48 被阅读0次

    需求描述:画箱式图或柱状图,进行坐标轴翻转后,默认情况下x轴跑到最下边,吧最下面的刻度调整到最上面。


    下面以ToothGrowth为例:
    rm(list = ls())
    library(tidyverse)
    library(ggsci)
    data(ToothGrowth)
    head(ToothGrowth)
    ToothGrowth$dose <- factor(ToothGrowth$dose)
    ggplot(ToothGrowth,aes(dose,len,fill=supp))+
      scale_fill_lancet()+
      geom_boxplot()+
      theme_bw()+
      labs(x="",y="Dose")+
      coord_flip()
    

    由于未翻转前,默认x轴刻度在左侧,因此导致后出现在了最下方。如果未翻转前改x轴刻度为右侧,会是什么效果哩?

    ggplot(ToothGrowth,aes(dose,len,fill=supp))+
      scale_fill_lancet()+
      geom_boxplot()+
      theme_bw()+
      labs(x="",y="Dose")+
      scale_y_continuous(expand = c(0,0),position = "right")+
      coord_flip()
    

    神奇的事情发生了,竟然达到了我们的目的!

    核心函数:
    scale_y_continuous(expand = c(0,0),position = "right")

    体会:
    绘图的过程中,不断思考绘图的底层逻辑,往往会有意想不到的收获。

    相关文章

      网友评论

        本文标题:【R>>ggplot2】坐标轴刻度位置调整

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