我试图制作一个带有滑块的图形图形,根据几种分类方案对点进行着色。 这是一个例子
library(plotly)
library(reshape2)
# create data
size = 100
groups = 8
x = as.data.frame(matrix(runif(2*size),size,2))
colnames(x)[1:2]=c('x','y')
for(i in 1:groups)
x[[paste0('set',i)]] = factor(sample(i,size,replace=T))
mx = melt(x,measure.vars=paste0("set",1:groups))
colnames(mx)[3:4] = c("set","group")
我希望在滑块中包含以下图表
p1 = ggplot(data=subset(mx,set=="set1"),aes(x=x,y=y,color=factor(group))) + geom_point() + theme_minimal() + labs(x="",y="")
ggplotly(p1)
p2 = ggplot(data=subset(mx,set=="set2"),aes(x=x,y=y,color=factor(group))) + geom_point() + theme_minimal() + labs(x="",y="")
ggplotly(p2)
p3 = ggplot(data=subset(mx,set=="set3"),aes(x=x,y=y,color=factor(group))) + geom_point() + theme_minimal() + labs(x="",y="")
ggplotly(p3)
# etc
我尝试过以下操作,但结果只给了我第一个颜色组的成员。
# plot
p = ggplot(data=mx,aes(x=x,y=y,color=factor(group),group=set,frame=set)) + geom_point() + theme_minimal() + labs(x="",y="")
ggplotly(p) %>% animation_opts(frame=1000,transition=600,redraw=F)
感谢。
答案 0 :(得分:0)
您可以将每个群集添加为单独的跟踪,并定义滑块以仅显示一个群集/跟踪。
对于着色,您可以创建单独的数据框,并为每个簇编号指定不同的颜色,例如通过模拟ggplot着色方案。
gg_color_hue <- function(n) {
hues = seq(15, 375, length = n + 1)
hcl(h = hues, l = 65, c = 100)[1:n]
}
colors = data.frame(group=c(1:groups), color=gg_color_hue(8))
注意:这需要Plotly
的开发人员版本。
完整代码
require(plotly)
library(reshape2)
#ggPlot colors, http://stackoverflow.com/questions/8197559/emulate-ggplot2-default-color-palette
gg_color_hue <- function(n) {
hues = seq(15, 375, length = n + 1)
hcl(h = hues, l = 65, c = 100)[1:n]
}
# create data
size = 100
groups = 8
x = as.data.frame(matrix(runif(2*size),size,2))
for(i in 1:groups) {
x[[paste0('set',i)]] = factor(sample(i, size, replace = T))
}
colnames(x)[1:2] = c('x', 'y')
mx = melt(x,
measure.vars = paste0("set",1:groups)
)
colnames(mx)[3:4] = c("set","group")
#create an empty plot
pp <- plot_ly()
#the steps for the slider
steps <- list()
colors = data.frame(group=c(1:groups), color=gg_color_hue(8))
for(i in 1:groups) {
x[[paste0('set',i)]] = factor(sample(i,size,replace=T))
df <- subset(mx, set == paste("set", i, sep=''))
pp <- add_trace(pp,
type = 'scatter',
x = df$x,
y = df$y,
mode = 'markers',
type = 'scatter',
name = paste('Cluster', i),
marker=list(color = colors$color[match(df$group, colors$group)]),
visible = (i == 1) #hide all but the first trace
)
#define each individual step
step <- list(args = list('visible', rep(FALSE, groups)),
method = 'restyle',
label = paste('Cluster', i))
step$args[[2]][i] = TRUE
steps[[i]] = step
}
pp <- pp %>% layout(sliders = list(list(active = groups,
currentvalue = list(prefix = "Clustering: "),
steps = steps)))
pp