简体   繁体   English

R中的散点图文本标签

[英]Scatter plot Text labels in R

我正在绘制分类变量与连续变量,年龄与吸烟习惯的关系图 Below is the code. 下面是代码。

stripchart(Age~Smoke, data = survey_clean_data , pch=16 , col = "blue", method = "jitter" ,main = "AGE VS SMOKE",na.rm = T)

I want to add labels to it like below image, 我想为其添加标签,如下图所示, 在此处输入图片说明

I tried several options.. but it is getting written on top of of other. 我尝试了几种选择..但是它被写在其他之上。

means = c(paste("mean_Age =",roumean(survey_clean_data[Smoke == "Heavy","Age"],na.rm =T)),
          paste("mean_Age =",mean(survey_clean_data[Smoke == "Never","Age"],na.rm =T)),
          paste("mean_Age =",mean(survey_clean_data[Smoke == "Regul","Age"],na.rm =T)),
          paste("mean_Age =",mean(survey_clean_data[Smoke == "Occas","Age"],na.rm =T)))


text(50,survey_clean_data$Smoke,labels =  means)

DATA: library(MASS) attach(survey) 数据:库(MASS)附加(调查)

There are a few problems with your code. 您的代码有一些问题。 The main thing is that you are sending text() four labels (the contents of means ), but a number of y-coordinates equal to the number of data points, since you are sending it survey_clean_data . 最主要的是,你要发送text()四个标签(内容means ),但一些y坐标等于数据点的数量,因为你是在发送survey_clean_data R tries to equalize these uneven vectors, resulting in the over plotting. R试图均衡这些不均匀向量,从而导致绘制过度。

Instead, you might do (data are artificial since you didn't provide any): 相反,您可以这样做(数据是人为的,因为您没有提供任何数据):

stripchart(Age~Smoke, data = survey_clean_data , pch=16 , col = "blue", method = "jitter" ,main = "AGE VS SMOKE",na.rm = T)

means <- aggregate(Age~Smoke, data = survey_clean_data, FUN = mean) # mean of each category
means$y <- 1:4 # add y-coordinates for each category

with(means, text(50, Smoke, labels = sprintf('Mean Age = %0.1f', Age))) # plot text labels on top of stripchart

Result: 结果:

在此处输入图片说明

answer give by jdobres worked fine. jdobres给出的答案效果很好。 The below is one more solution. 以下是另一种解决方案。

add ylim=c(0.8,4.2) parameter to the scatterplot. 在散点图中添加ylim=c(0.8,4.2)参数。 You can adjust these ranges from c(1,4) to c(0.8,4.2). 您可以将范围从c(1,4)调整为c(0.8,4.2)。 The later one worked for me. 后来的一个为我工作。

stripchart(Age~Smoke, data = survey_clean_data , pch=16 , col = 634, method = "jitter" ,main = "AGE VS SMOKE",na.rm = T,ylim=c(0.8,4.2))

With the below line you can adjust the vertical height of the text. 在下面的行中,您可以调整文本的垂直高度。 eg: +0.1, -0.1 etc 例如:+ 0.1,-0.1等

text(50,c(1:4)+0.1,means)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM