R语言ggplot2包之坐标轴

引言

我们还可以对图形中的坐标轴进行处理,包括x、y轴对换、设定坐标轴范围、刻度线修改与去除等等。要想对图形玩得转,坐标轴处理精通不可或缺。

坐标轴对换

我们使用coord_flip()函数来对换坐标轴。

library(ggplot2)
library(gcookbook)
ggplot(PlantGrowth, aes(x=group, y=weight)) + geom_boxplot()
ggplot(PlantGrowth, aes(x=group, y=weight)) + geom_boxplot() + coord_flip()

这里写图片描述
这里写图片描述
置换x、y轴时有时候会导致某一坐标轴的坐标被逆转。比如说原x轴的数据是从左往右阅读的,在对换后,原来数据会从下往上给呈现。有时这是个问题。如果x是因子,我们可以对其用带参数limits=rev(levels(…))的函数scale_x_discrete()进行修正。

如果是连续变量,我们可以使用函数scale_y_reverse 或者scale_x_reverse来逆转坐标轴。

如果我们想改变分类变量的显示顺序,可以设置scale_x_discrete() or scale_y_discrete()函数就行。

#因子坐标轴
ggplot(PlantGrowth, aes(x=group, y=weight)) + geom_boxplot() + coord_flip() +
scale_x_discrete(limits=rev(levels(PlantGrowth$group)))
#连续变量的逆转
ggplot(PlantGrowth, aes(x=group, y=weight)) + geom_boxplot() + scale_y_reverse()
#改变分类变量顺序
ggplot(PlantGrowth, aes(x=group, y=weight)) + geom_boxplot()+scale_x_discrete(limits=c("trt1","ctrl","trt2"))

这里写图片描述
这里写图片描述

  • 25
    点赞
  • 187
    收藏
    觉得还不错? 一键收藏
  • 8
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值