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

2022-11-03 14:55:33 浏览数 (2)

[toc]

直接看图解释

image.png

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

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

1.横坐标从0开始

首先将gear与carb转成factor

代码语言:javascript复制
# 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。

代码语言:javascript复制
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可以更改柱状图的颜色。主题里面可去除网格线

代码语言:javascript复制
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

0 人点赞