如何在 R 中使用 ggplot2 抑制垂直网格线?
在本文中,我们将讨论使用 R 编程语言在 ggplot 中抑制垂直网格线的各种方法。
我们先画一个不做任何改动的正则图,所以区别是可以追溯的:
R
library("ggplot2")
function1<- function(x){x**2}
function2<-function(x){x**3}
function3<-function(x){x/2}
function4<-function(x){2*(x**3)+(x**2)-(x/2)}
df=data.frame(x=-2:2,
values=c(function1(-2:2),
function2(-2:2),
function3(-2:2),
function4(-2:2)),
fun=rep(c("function1","function2",
"function3","function4"))
)
ggplot(df,aes(x,values,col=fun))+geom_line()
R
library("ggplot2")
function1<- function(x){x**2}
function2<-function(x){x**3}
function3<-function(x){x/2}
function4<-function(x){2*(x**3)+(x**2)-(x/2)}
df=data.frame(x=-2:2,
values=c(function1(-2:2),
function2(-2:2),
function3(-2:2),
function4(-2:2)),
fun=rep(c("function1","function2",
"function3","function4"))
)
ggplot(df,aes(x,values,col=fun))+geom_line()+
scale_x_continuous(breaks=NULL)
R
library("ggplot2")
library("ggExtra")
function1<- function(x){x**2}
function2<-function(x){x**3}
function3<-function(x){x/2}
function4<-function(x){2*(x**3)+(x**2)-(x/2)}
df=data.frame(x=-2:2,
values=c(function1(-2:2),
function2(-2:2),
function3(-2:2),
function4(-2:2)),
fun=rep(c("function1","function2",
"function3","function4"))
)
ggplot(df,aes(x,values,col=fun))+geom_line()+
removeGrid(y=FALSE)
输出:
方法 1:使用 scale_x_continuous()
scale_x_continuous()函数可用于处理垂直网格线的外观和吸引力。此函数的breaks 属性可以设置为NULL,以将它们从绘图中删除。
Syntax: scale_x_continuous(breaks=NULL)
示例:使用 scale_x_continuous() 抑制垂直网格线
电阻
library("ggplot2")
function1<- function(x){x**2}
function2<-function(x){x**3}
function3<-function(x){x/2}
function4<-function(x){2*(x**3)+(x**2)-(x/2)}
df=data.frame(x=-2:2,
values=c(function1(-2:2),
function2(-2:2),
function3(-2:2),
function4(-2:2)),
fun=rep(c("function1","function2",
"function3","function4"))
)
ggplot(df,aes(x,values,col=fun))+geom_line()+
scale_x_continuous(breaks=NULL)
方法二:使用ggExtra包
这个包有一个名为 removeGrid() 的函数,顾名思义,它用于抑制绘图的网格线。
Syntax: removeGrid(x, y)
Where, y attribute of this function should be set to false in order to suppress vertical gridlines in particular.
示例:使用 ggExtra 抑制垂直网格线
电阻
library("ggplot2")
library("ggExtra")
function1<- function(x){x**2}
function2<-function(x){x**3}
function3<-function(x){x/2}
function4<-function(x){2*(x**3)+(x**2)-(x/2)}
df=data.frame(x=-2:2,
values=c(function1(-2:2),
function2(-2:2),
function3(-2:2),
function4(-2:2)),
fun=rep(c("function1","function2",
"function3","function4"))
)
ggplot(df,aes(x,values,col=fun))+geom_line()+
removeGrid(y=FALSE)
输出: