我注意到,在使用ggplot2
函数将plotly
绘图转换为交互式ggplotly
绘图时,可能会出现strange things。
我正在绘制一个“Punchcard情节”,这是一种呈现数据集4维的好方法:
df <- data.frame(cat1 = rep(c("a","b","c"), 3), cat2 = c(rep("A", 3),
rep("B", 3), rep("C", 3)), var1 = 1:9, var2 = 10:18)
ggplot(df, aes(x=cat1, y=cat2, size= var1, fill = var2)) +
geom_point(shape=21)
但是,当我使用ggplotly
转换为互动时,plotly
只提供了一个传说:
p <- ggplot(df, aes(x=cat1, y=cat2, size= var1, fill = var2)) +
geom_point(shape=21)
ggplotly(p)
为什么plotly
会这样做,我该如何避免这种行为?
看到我遇到越来越多这些奇怪的事情 - 任何人都有链接到某个地方我可以阅读ggplotly
如何运作,以某种方式我将来可以解决这些问题?
答案 0 :(得分:5)
第二个传奇在转换过程中迷失了(或者至少我在数据中找不到)。您可以查看ggplotly
的结果并修改从原始数据到布局的所有内容,例如gp[['x']][['layout']]
将包含从ggplotly
传递的所有布局变量。
更多代码行,但您可以完全控制图表的所有方面。
library(plotly)
df <- data.frame(cat1 = rep(c("a","b","c"), 3),
cat2 = c(rep("A", 3),
rep("B", 3),
rep("C", 3)),
var1 = 1:9,
var2 = 10:18)
size_multi <- 2 #multiplies your size to avoid pixel sized objects
color_scale <- list(c(0, "#000000"), list(1, "#00BFFF"))
p <- plot_ly(df,
type='scatter',
mode='markers',
x = ~cat1,
y = ~cat2,
marker = list(color = ~var2,
size=~var1 * size_multi,
colorscale = color_scale,
colorbar = list(len = 0.8, y = 0.3),
line = list(color = ~var2,
colorscale = color_scale,
width = 2)
),
showlegend = F)
#adds some dummy traces for the punch card markers
markers = c(min(df$var1), mean(df$var1), max(df$var1))
for (i in 1:3) {
p <- add_trace(p,
df,
type = 'scatter',
mode = 'markers',
showlegend = T,
name = markers[[i]],
x = 'x',
y = 'x',
marker = list(size = markers[[i]] * size_multi,
color='rgba(255,255,255,0)',
showscale = F,
line = list(color = 'rgba(0,0,0,1)',
width = 2))
)
}
#fix the coordinate system
spacer <- 0.2
p <- layout(p, xaxis=list(range=c(-spacer, length(levels(df$cat1)) - 1 + spacer)), yaxis=list(range=c(-spacer, length(levels(df$cat1)) - 1 + spacer)))
p