[英]R, How to change color of plotly 3d surface?
如何將色階從默認的紫色更改為黃色? 我嘗試將顏色和色階參數添加到add_trace(),但它會引發錯誤。
具有默認顏色的可重現代碼:
library(plotly); library(reshape2); library(tidyverse)
sleep <- read.table("http://www.statsci.org/data/general/sleep.txt", header=T)
sleep <- na.omit(sleep)
sleep <- mutate(sleep, logTotalSleep = log(TotalSleep))
sleep_mod <- lm(logTotalSleep ~ Gestation + Danger, data=sleep)
# Graph Resolution (more important for more complex shapes)
graph_reso <- 0.5 #0.05
# Setup Axis
axis_x <- seq(min(sleep$Gestation), max(sleep$Gestation), by = graph_reso)
axis_y <- seq(min(sleep$Danger), max(sleep$Danger), by = graph_reso)
# Sample points
sleep_surface <- expand.grid(Gestation = axis_x,
Danger = axis_y,
KEEP.OUT.ATTRS = F)
sleep_surface$TotalSleep <- exp(predict.lm(sleep_mod, newdata = sleep_surface)) # exp to remove ln() from y
sleep_surface <- acast(sleep_surface, Danger ~ Gestation, value.var = "TotalSleep") #y ~ x
# Plot
p <- plot_ly(data = sleep) %>%
add_trace(x = ~Gestation, y = ~Danger, z = ~TotalSleep,
type = "scatter3d", mode = "markers",
opacity = .8) %>%
add_trace(z = sleep_surface,
x = axis_x,
y = axis_y,
type = "surface") %>%
layout(scene = list(xaxis = list(title = 'Gestation Period (days)'),
yaxis = list(title = 'Danger Index'),
zaxis = list(title = 'Hours of Sleep')))
p
您可以定義自己的色階並將其添加到add_trace
,您可以在其中定義曲面圖。
colorscale = list(c(0, 1), c("tan", "blue"))
這給你以下raph
完整的代碼
library(plotly)
library(reshape2)
sleep <- read.table("http://www.statsci.org/data/general/sleep.txt", header=T)
sleep <- na.omit(sleep)
sleep <- mutate(sleep, logTotalSleep = log(TotalSleep))
sleep_mod <- lm(logTotalSleep ~ Gestation + Danger, data=sleep)
graph_reso <- 0.5
axis_x <- seq(min(sleep$Gestation), max(sleep$Gestation), by = graph_reso)
axis_y <- seq(min(sleep$Danger), max(sleep$Danger), by = graph_reso)
sleep_surface <- expand.grid(Gestation = axis_x,
Danger = axis_y,
KEEP.OUT.ATTRS = F)
sleep_surface$TotalSleep <- exp(predict.lm(sleep_mod, newdata = sleep_surface)) # exp to remove ln() from y
sleep_surface <- acast(sleep_surface, Danger ~ Gestation, value.var = "TotalSleep") #y ~ x
p <- plot_ly(data = sleep) %>%
add_trace(x = ~Gestation, y = ~Danger, z = ~TotalSleep,
type = "scatter3d", mode = "markers",
opacity = .8) %>%
add_trace(z = sleep_surface,
x = axis_x,
y = axis_y,
type = "surface", colorscale = list(c(0, 1), c("tan", "blue")))
p
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.