我已经注意到,使用ggplot2
函数将plotly
图转换为交互式ggplotly
图时,可能会出现strange things。
我正在绘制“打孔卡图”,这是表示数据集的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
的工作方式的地方,从而可以自己解决这些问题? 最佳答案
第二个图例在转换过程中丢失了(或者至少我在数据中找不到)。您可以查看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
关于r - R plotly:用ggplotly转换ggplot2时,保留两个图例的外观,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42820823/