R曲线图

时间:2017-11-21 05:56:33

标签: r plotly

我有一个包含三个变量的数据集,即性别,年龄和BMI,这是数据样本:

我试图使用plotly包在r中绘制折线图,​​其中X轴显示BMI值,Y轴显示Age和Gender绘制两行作为对应于BMI和Age的值。我正在尝试这些代码但无法获得正确的输出。这是我的代码

    library(plotly)
data<-read.csv("abc1.csv")
p <- plot_ly(data, x = ~BMI, y = ~Age, type = 'scatter', mode = 'lines',
             linetype = ~Gender,line = list(color = 'rgb(205, 12, 24)', width = 4)) %>%
  layout(title = "Line chart",
         xaxis = list(title = "Age"),
         yaxis = list (title = "BMI"))
p

这是我的控制台输出enter image description here

先谢谢。

1 个答案:

答案 0 :(得分:0)

希望您正在寻找最合适的折线图

#sample data
df <- data.frame(Age=c(75.6, 81.9, 81.9,83.2,84.6,84.9,88,89.1),
                 Gender=c('M','F','F','M','M','F','M','M'),
                 BMI=c(16.2,17.3,14.9,19.6,15.5,14.7,15,14.8))

gender <- levels(df$Gender)
col <- c('red','green','blue')

library(plotly)
p <- plot_ly()
for (i in 1:length(gender)) {
  p <- p %>%
    add_lines(data = df[df$Gender==gender[i],],
              x = ~BMI,
              y = fitted(lm(data = df[df$Gender==gender[i],], Age ~ BMI)),
              line = list(color = col[i]),
              name = gender[i]) %>%
    add_markers(data = df[df$Gender==gender[i],], 
                x = ~BMI,
                y = ~Age,
                symbol = ~Gender,
                marker=list(color = col[i]))
}
p %>%
  layout(xaxis = list(title = "BMI"), yaxis = list(title = "Age"), title="BMI-Age Line Chart")