如何解决为R散点图做出正确的可视化
我有一个数据框:
x = data.frame(metrics=c("type1","type1","orders","mean","mean"),hr=c(6,7,8,6,8),actual=c(14,20,34,22,24,27,56,12,11,15,45,78,89,111,123,156),time_pos=c("today","yesterday","today","yesterday"))
以下是绘制散点图子图的代码:
library(plotly)
plot <- function(df) {
.pal <- RColorBrewer::brewer.pal(3,"Set2")[c(1,3)]
subplotList <- list()
for(metric in unique(df$metrics)){
showlegend <- metric == unique(df$metrics)[1]
subplotList[[metric]] <- df[df$metrics == metric,] %>%
plot_ly(
x = ~ hr,y = ~ actual,color = ~ time_pos,colors = .pal,legendgroup = ~time_pos,showlegend = showlegend,hoverinfo = "text",hovertemplate = paste(
"<b>%{text}</b><br>","%{xaxis.title.text}: %{x:+.1f}<br>","%{yaxis.title.text}: %{y:+.1f}<br>","<extra></extra>"
),type = "scatter",mode = "lines+markers",marker = list(
size = 7,color = "white",line = list(width = 1.5)
),width = 700,height = 620
) %>%
add_annotations(
text = ~metrics,x = 0.5,y = 1,yref = "paper",xref = "paper",xanchor = "center",yanchor = "bottom",showarrow = FALSE,font = list(size = 15)
) %>%
layout(autosize = T,legend = list(font = list(size = 8)))
}
subplot(subplotList,nrows = length(subplotList),margin = 0.05)
}
plot(x)
这是一张图:
如您所见,例如在第一个子图中,第一个标记同时连接到第二个和第三个标记,尽管它只能与第二个标记连接。第二个子图也会发生相同的情况。我该如何解决?
解决方法
可以通过相应地对data.frame进行排序来实现:
library(plotly)
x = data.frame(metrics=c("type1","type1","orders","mean","mean"),hr=c(6,7,8,6,8),actual=c(14,20,34,22,24,27,56,12,11,15,45,78,89,111,123,156),time_pos=c("today","yesterday","today","yesterday"))
x <- x[order(x$hr),]
plot <- function(df) {
.pal <- RColorBrewer::brewer.pal(3,"Set2")[c(1,3)]
subplotList <- list()
for(metric in unique(df$metrics)){
showlegend <- metric == unique(df$metrics)[1]
subplotList[[metric]] <- df[df$metrics == metric,] %>%
plot_ly(
x = ~ hr,y = ~ actual,color = ~ time_pos,colors = .pal,legendgroup = ~time_pos,showlegend = showlegend,hoverinfo = "text",hovertemplate = paste(
"<b>%{text}</b><br>","%{xaxis.title.text}: %{x:+.1f}<br>","%{yaxis.title.text}: %{y:+.1f}<br>","<extra></extra>"
),type = "scatter",mode = "lines+markers",marker = list(
size = 7,color = "white",line = list(width = 1.5)
),width = 700,height = 620
) %>%
add_annotations(
text = ~metrics,x = 0.5,y = 1,yref = "paper",xref = "paper",xanchor = "center",yanchor = "bottom",showarrow = FALSE,font = list(size = 15)
) %>%
layout(autosize = T,legend = list(font = list(size = 8)))
}
subplot(subplotList,nrows = length(subplotList),margin = 0.05)
}
plot(x)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。