2016-09-21 51 views
0

I am plotting categorical variable vs continuous variable, AGE vs Smoking habits 以下是代码。Scatter plot R中的文字标签

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

我要标签添加到它像下面的图像, enter image description here

我试过几个选项..但它是越来越对另一个的上面写的。

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:图书馆(MASS)连接(调查)

+1

对于R标签我们要求您提供可重现的例子(即,数据和代码)。如果你提供的数据,然后我可以告诉你如何做到这一点。 –

回答

1

有你的代码的几个问题。主要的是你发送text()四个标签(means的内容),但一些Y坐标等于数据点的数量,因为你发送它survey_clean_data。 R试图平衡这些不均匀的矢量,导致过度绘图。

相反,你可能会做(数据都是人造的,因为你没有提供任何):

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 

结果:

enter image description here

0

答案由jdobres给工作得很好。以下是另一个解决方案。

ylim=c(0.8,4.2)参数添加到散点图。您可以调整这些范围,从c(1,4)到c(0.8,4.2)。后者为我工作。

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)) 

通过下面的行,您可以调整文本的垂直高度。 例如:0.1,-0.1等

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