如何防止轴在ggplot2中相交 [英] how to prevent axes from intersecting in ggplot2

查看:39
本文介绍了如何防止轴在ggplot2中相交的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用ggplot2绘制一些对数转换后的数据的折线图,这些数据都具有较大的值(在10 ^ 6到10 ^ 8之间);由于轴不是从零开始,所以我不希望它们在原点"处相交.

I'm using ggplot2 to make line graphs of some log-transformed data that all have large values (between 10^6 and 10^8); since the axes doesn't start at zero, I'd prefer not to have them intersect at the "origin."

这是当前轴的外观:

我更喜欢从基本图形中获取某种东西(但我另外在ggplot2中使用了 geom_ribbon 和其他我非常喜欢的奇特的东西,所以我更喜欢找到一种ggplot2解决方案):

I'd prefer something more like one gets from base graphics (but I'm additionally using geom_ribbon and other fancy things I really like in ggplot2, so I'd prefer to find a ggplot2 solution):

这是我目前正在做的事情:

Here's what I'm doing currently:

mydata <- data.frame(Day = rep(1:8, 3), 
  Treatment = rep(c("A", "B", "C"), each=8), 
  Value = c(7.415929, 7.200486, 7.040555, 7.096490, 7.056413, 7.143981, 7.429724, 7.332760, 7.643673, 7.303994, 7.343151, 6.923636, 6.923478, 7.249170, 7.513370, 7.438630, 7.209895, 7.000063, 7.160154, 6.677734, 7.026307, 6.830495, 6.863329, 7.319219))

ggplot(mydata, aes(x=Day, y=Value, group=Treatment)) 
  + theme_classic() 
  + geom_line(aes(color = Treatment), size=1) 
  + scale_y_continuous(labels = math_format(10^.x)) 
  + coord_cartesian(ylim = c(6.4, 7.75), xlim=c(0.5, 8))

plot(mydata$Day, mydata$Value, frame.plot = F)  #non-intersecting axes

推荐答案

此问题的解决方法是使用 theme(axis.line = element_blank())删除轴线,然后添加错误的轴带有 geom_segment()的行-一条用于x轴,另一条用于y轴. x y xend yend 值是根据您的绘图确定的(取最小值和最大值)显示在每个对应轴的图上)和 coord_cartesian()中使用的轴限制(限制的最小值,以确保绘制段来代替轴).

Workaround for this problem would be to remove axis lines with theme(axis.line=element_blank()) and then add false axis lines with geom_segment() - one for x axis and second for y axis. x, y , xend and yend values are determined from your plot (taken as the smallest and the largest values shown on plot for each corresponding axis) and axis limits used in coord_cartesian() (minimal value of limits to ensure that segment is plotted in place of axis).

ggplot(mydata, aes(x=Day, y=Value, group=Treatment)) +theme_classic() +
 geom_line(aes(color = Treatment), size=1) +
 scale_y_continuous(labels = math_format(10^.x))+ 
 coord_cartesian(ylim = c(6.4, 7.75), xlim=c(0.5, 8))+
 theme(axis.line=element_blank())+
 geom_segment(x=2,xend=8,y=6.4,yend=6.4)+
 geom_segment(x=0.5,xend=0.5,y=6.5,yend=7.75)

这篇关于如何防止轴在ggplot2中相交的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆