从ggplot2的2.2.0版本开始,它本身就支持图形的第二个轴。因此,cowplot的函数switch_axis_position()
已经过时了。下面是一些可以用ggplot2实现的例子。
require(cowplot)require(grid) # for unit()theme_set(theme_cowplot(font_size=12)) # reduce default font sizep1 <- ggplot(mtcars, aes(mpg, disp)) + geom_line(colour = "blue")# the following code only works for ggplot2 2.2.0 or laterif (packageVersion("ggplot2")>"2.1.0") p1 + theme_gray() + scale_y_continuous(position = "right")
if (packageVersion("ggplot2")>"2.1.0") p1 + theme_bw() + scale_x_continuous(sec.axis = dup_axis())
if (packageVersion("ggplot2")>"2.1.0") p1 + scale_x_continuous(sec.axis = dup_axis()) + scale_y_continuous(sec.axis = dup_axis())
if (packageVersion("ggplot2")>"2.1.0") p1 + theme(axis.ticks.length = unit(0.3, "cm"), axis.text.x = element_text(margin = margin(0.2, unit = "cm"))) + scale_x_continuous(sec.axis = dup_axis()) + scale_y_continuous(sec.axis = dup_axis())
image.png
这同样适用于离散轴:
mtcars2 <- mtcars[1:15, ] mtcars2$name <- row.names(mtcars2)# the following code only works for ggplot2 2.2.0 or laterif (packageVersion("ggplot2")>"2.1.0"){ ggplot(mtcars2, aes(x = name, y = mpg, fill = name)) + geom_bar(stat = 'identity', position = "identity") + scale_y_reverse() + guides(fill = FALSE) + theme(axis.text.x.top = element_text(angle = 90, vjust=0.5, hjust=0)) + scale_x_discrete(position = "top") }
作者:王诗翔
链接:https://www.jianshu.com/p/31d8860b5fad
点击查看更多内容
为 TA 点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦