我需要在散点图上绘制两个加速度与vs-mpg的斜率, 轻型汽车的一个斜坡和重型汽车的一个斜坡。我创造了这个:
cars_light <- cars_log[cars_log$log.weight. <= log(mean(cars$weight)), ]
cars_heavy <- cars_log[cars_log$log.weight. > log(mean(cars$weight)),]
cars_log$wt_cat <- ifelse(cars_log$log.weight. > log(mean(cars$weight)), 'heavy', 'light')
到目前为止,我已经通过这样做创建了散点图:
plot_ly(
data = cars_log,
type = "scatter",
x = ~log.acceleration.,
y = ~ log.mpg.,
color = ~ factor(wt_cat),
colors = c("#8bc34a", "#ff5722"),
marker = list(size = 10, opacity = 0.6)
) %>%
layout(title = "Heavy cars VS light cars")
这给了我这个结果:
现在,我想为重型汽车创建一个斜坡,为轻型汽车创建另一个斜坡,我知道我需要使用add_ribbons的情节跟踪,但我无法弄清楚如何生成它。我在使用plotly计算lm时遇到了问题。 我可以用ggplot做同样的事情,但我不知道如何用情节做到这一点..
ggplot(cars_log, aes_string('log.acceleration.', 'log.mpg.')) +
geom_point(aes(color = factor(wt_cat))) +
geom_smooth(method = 'lm', aes(color = factor(wt_cat)))
这是我的数据样本:
> cars_log[1:5,]
log.mpg. log.cylinders. log.displacement. log.horsepower. log.weight. log.acceleration. model_year origin
1 2.890372 2.079442 5.726848 4.867534 8.161660 2.484907 70 1
2 2.708050 2.079442 5.857933 5.105945 8.214194 2.442347 70 1
3 2.890372 2.079442 5.762051 5.010635 8.142063 2.397895 70 1
4 2.772589 2.079442 5.717028 5.010635 8.141190 2.484907 70 1
5 2.833213 2.079442 5.710427 4.941642 8.145840 2.351375 70 1
答案 0 :(得分:2)
您可以使用data
功能。其主要的三个论点是:
x
数据ymin
x values ymax
功能区的下限broom::augment()
功能区的上限由于缺少最小数据集,我采用了这个:plotly regression line R用于一个封闭的问题(即在R Plotly中绘制回归线)。使用此数据集,下面是一个示例,其中回归在Plotly外部完成,其输出使用library(plotly)
library(broom)
data(airquality)
airq <- airquality %>%
filter(!is.na(Ozone))
fit <- lm(Ozone ~ Wind, data = airq)
airq %>%
plot_ly(x = ~Wind, name = 'Scatter') %>%
add_markers(y = ~Ozone) %>%
add_ribbons(data = augment(fit),
ymin = ~.fitted - 1.96 * .se.fit,
ymax = ~.fitted + 1.96 * .se.fit,
line = list(color = 'rgba(7, 164, 181, 0.05)'),
fillcolor = 'rgba(7, 164, 181, 0.2)',
name = '95% ribbon')
格式化,然后用于创建功能区:
firebase logout