美文网首页
ggplot画图:y坐标从0开始,去除x横坐标与柱状图之间的间隙

ggplot画图:y坐标从0开始,去除x横坐标与柱状图之间的间隙

作者: jamesjin63 | 来源:发表于2021-01-06 10:06 被阅读0次

    [toc]

    直接看图解释


    image.png

    由上图,我们可以看到,1)x横坐标与柱状图有一些距离,那么现在我们要去掉这个距离。怎么办?,2)还发现,y坐标与柱状图也是有距离的。咋去除?

    接下来,我们以mtcar数据为例,展示如果去除这些间隙。

    1.横坐标从0开始

    首先将gear与carb转成factor

    # libraries
    library(ggthemes)
    library(tidyverse)
    df=mtcars %>% mutate(gear=factor(gear),
                         cyl=factor(cyl))
    # histgram
    p=ggplot(df, aes(x = gear,y=mpg, fill = cyl)) + 
      geom_bar(position="dodge", stat="identity",width=0.65)
    
    # start from 0 in x-axis
    p +
    scale_y_continuous(expand = c(0,0),limits = c(0,30)) 
    
    image.png

    2.纵坐标从0开始

    这里有些trick,因为factor为横坐标,但是加载scale_x_continuous出错,
    所以在scale_x_continuous里面,自定义x-labels。

    df=mtcars %>% mutate(gear=(gear),
                         cyl=factor(cyl))
    # histgram
    p=ggplot(df, aes(x = gear,y=mpg, fill = cyl)) + 
      geom_bar(position="dodge", stat="identity",width=0.65)
    # start from 0 in y-axis
    p+scale_x_continuous(expand = expansion(mult = c(0,0)))
    
    # add x-labels
    p=ggplot(df, aes(x = gear,y=mpg, fill = cyl)) + 
      geom_bar(position="dodge", stat="identity",width=0.65)+
      scale_x_continuous(expand = expansion(mult = c(0,0)),
                         breaks = c(3,4,5),
                         labels = c(3,4,5))
    p
    
    image.png image.png

    2.去除网格线与legend

    scale_fill_manual可以更改柱状图的颜色。主题里面可去除网格线

    p+scale_y_continuous(expand = c(0,0),limits = c(0,30)) +
      scale_fill_manual(
        #expand = c(0, 0), limits = c(0, NA),
    values=c("#1F78B4","#FFB300","#FA2017","#33A02C","#DD8EB4","#6A3D9A","#666666"))+
      theme_bw() +
      theme(#legend.position = "none",
        axis.text.x=element_text(angle=30,hjust=1),
        text = element_text(size=10,face="bold"),
        plot.background = element_blank(),
        panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(),
        panel.border = element_blank(),
        strip.text.y = element_blank(), 
        strip.text = element_text(size=10,face="bold"),
        strip.background = element_blank(),
        axis.line = element_line(color = 'black'))+
      labs(y="mpg values",
           x="Gear group",fill="carb")
    
    image.png

    参考文献

    1. Ggplot include 0 in axis
    2. Starting bars and histograms at zero in ggplot2
    3. Force the origin to start at 0

    相关文章

      网友评论

          本文标题:ggplot画图:y坐标从0开始,去除x横坐标与柱状图之间的间隙

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