如何在R的ggplot2中创建点状垂直线?
要使用ggplot2创建垂直线,我们可以使用ggplot2包的geom_vline函数,如果想要点状垂直线,则在同一个函数中将linetype设置为3。要绘制线条,我们必须提供xintercept,因为线条将从X轴开始。
查看下面的例子来了解它是如何工作的。
示例
以下代码片段创建一个样本数据框:
x<-rpois(20,5) y<-rpois(20,2) df<-data.frame(x,y) df
创建了以下数据框:
x y 1 5 2 2 3 4 3 6 2 4 3 4 5 4 2 6 5 2 7 7 1 8 4 2 9 3 2 10 4 4 11 6 2 12 2 2 13 7 1 14 7 1 15 6 1 16 7 1 17 7 2 18 7 1 19 6 3 20 4 3
要加载ggplot2包并在x和y之间创建点状图,并在X=5处添加垂直线,请将以下代码添加到上面的代码片段中:
library(ggplot2) ggplot(df,aes(x,y))+geom_point()+geom_vline(xintercept=5)
输出
如果将上面给出的所有代码片段作为一个程序执行,则会生成以下输出:
现在,要在x和y之间创建点状图,并在X=5处添加点状垂直线,请将以下代码添加到上面的代码片段中:
ggplot(df,aes(x,y))+geom_point()+geom_vline(xintercept=5,linetype=3)
Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.
输出
如果将上面给出的所有代码片段作为一个程序执行,则会生成以下输出:
广告