用rChart标记上面的点

时间:2014-06-19 10:16:39

标签: r plot rcharts

我有一个用nPlot创建的图表,我有两个X轴和Y轴变量,我想添加第三个变量,当我在图表上指出我的点时,我可以看到它。 例如,如果一个人有X =年龄,Y =高,Z =姓名,我希望能够根据年龄和点上方不同人的姓名来看到身高的变化。

以下是一个例子:

library(rCharts)
age <- c(1:20)
tall <- seq(0.5, 1.90, length = 20)
name <- paste(letters[1:20], 1:20, sep = "")
df <- data.frame(age, tall, name)
plot <- nPlot(x = "age", y = "tall", data = df, type = "scatterChart")
plot$xAxis(axisLabel = "the age")
plot$yAxis(axisLabel = "the tall")
plot  

2 个答案:

答案 0 :(得分:3)

您可以使用tooltipContent选项:

library(rCharts)
age <- c(1:20)
tall <- seq(0.5, 1.90, length = 20)
name <- paste(letters[1:20], 1:20, sep = "")
df <- data.frame(age = age, tall = tall, name = name)
n1 <- nPlot(age ~ tall ,data = df, type = "scatterChart")
n1$xAxis(axisLabel = "the age")
n1$yAxis(axisLabel = "the tall", width = 50)
n1$chart(tooltipContent = "#! function(key, x, y, e ){ 
  var d = e.series.values[e.pointIndex];
  return 'x: ' + x + '  y: ' + y + ' name: ' + d.name
} !#")
n1

enter image description here

e.series是鼠标悬停的特定系列,e.pointIndex是系列值的索引。因此d = e.series.values[e.pointIndex]将为正在悬停的系列提供数据点。然后,d.name会提供name属性。

答案 1 :(得分:0)

我的R(3.0.2)版本无法下载rChart包,但我可以使用base编码回答您的问题。

> age <- c(1:20)
> tall <- seq(0.5, 1.90, length = 20)
> name <- paste(letters[1:20], 1:20, sep = "")
> df <- data.frame(age, tall, name)
> plot(x = df$age, y = df$tall, xlab = "the age", ylab = "the tall")  
> text(df$age, df$tall, labels = df$name, adj = c(1,-0.3))  #Applies text based on x, y inputs (e.g. age and tall)

enter image description here