如何在 R 的 ggplot2 图表中创建虚线水平线?


要在 R 的 ggplot2 图表中创建虚线水平线,我们可以按照以下步骤操作:

  • 首先,创建一个数据框。
  • 然后,使用 ggplot2 创建一个绘图。
  • 之后,使用 geom_hline 函数创建相同的绘图,其中水平线由 y 截距定义,其类型由 line type 参数定义。

创建数据框

让我们创建一个如下所示的数据框:

 实时演示

> x<-rnorm(20)
> y<-rnorm(20)
> df<-data.frame(x,y)
> df

执行后,上述脚本生成以下输出(此输出由于随机化而在您的系统上会有所不同):

         x       y
1 -0.2622735 0.050784727
2 -0.9453493 0.005828098
3 -0.5544653 -0.569278949
4   0.4988631 0.978485828
5   0.5389510 -2.328920035
6   0.4434926 1.099015564
7   0.2681379 0.760637085
8   1.5537351 0.172285069
9   0.9497421 -1.823161011
10 0.3323686 -1.394199992
11 0.2146744 0.538098034
12 0.8275667 -0.361978640
13 -0.4820211 0.477345035
14  0.4364038 -0.341711304
15 -0.4499373 0.854135140
16 1.6604468 -1.333167314
17 -0.4244539 0.989662861
18 1.3667020 -0.358490011
19 -1.5132316 2.234713443
20 0.8474354 1.162478362

使用 ggplot2 创建绘图

让我们在 x 和 y 之间创建一个散点图:

> x<-rnorm(20)
> y<-rnorm(20)
> df<-data.frame(x,y)
> library(ggplot2)
> ggplot(df,aes(x,y))+geom_point()

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

输出

创建带有虚线水平线的绘图

使用 geom_hline 在上述绘图中创建虚线水平线,其中 yintercept = 0.5 且 linetype = 2:

 实时演示

> x<-rnorm(20)
> y<-rnorm(20)
> df<-data.frame(x,y)
> library(ggplot2)
> ggplot(df,aes(x,y))+geom_point()+geom_hline(yintercept=0.5,linetype=2)

输出

更新于: 2021年8月13日

9K+ 浏览量

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告