需求描述:画箱式图或柱状图,进行坐标轴翻转后,默认情况下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")
体会:
绘图的过程中,不断思考绘图的底层逻辑,往往会有意想不到的收获。
网友评论