gpt4 book ai didi

r - 具有共享数据的多个 ggplot2 图表

转载 作者:行者123 更新时间:2023-12-02 02:11:08 24 4
gpt4 key购买 nike

如何在回收数据时对相同数据绘制多个图,但根据不同因素(列)以不同颜色绘制?这是 gridExtracowplot 的不同之处吗?

目标: 我的目标是直观地比较有效聚类相同数据的不同结果。 目前,我认为直观地比较 2-4 个聚类算法的最简单方法是将它们彼此相邻绘制。

因此,如何并排绘制不同颜色的相同数据?

挑战/规范:性能非常重要。我大约需要制作 30,000 个图表,每个图表有 450 - 480 个点。数据的“回收”至关重要。

我可以使用包cowplotgridExtra并排绘制它们。我今天刚刚开始使用 gridExtra,但它似乎可以回收数据,并且对于我的目的来说比owplot 更好。 更新: u/eipi10 证明,如果我在绘图之前收集列,facet_wrap 就可以工作。

设置

    #Packages
library(ggplot2)
library(cowplot)
library(gridExtra)
library(pryr) #memory profile

#Data creation
x.points <- c(1, 1, 1, 3, 3, 3, 5, 5, 5)
y.points <- c(1, 3, 5, 1, 3, 5, 1, 3, 5)
cl_vert <- c("A", "A", "A", "B", "B", "B", "C", "C", "C")
cl_hoz <- c("A", "B", "C", "A", "B", "C", "A", "B", "C")
cl_cent <- c("A","A","A","A", "B", "A","A","A","A")
df <- data.frame(x.points, y.points, cl_vert, cl_hoz, cl_cent)

绘制图表

    #Graph function and individual plots
graph <- function(data = df, Title = "", color.by, legend.position = "none"){
ggplot(data, aes(x = `x.points`, y = `y.points`)) +
geom_point(aes(color = as.factor(color.by))) + scale_color_brewer(palette = "Set1") +
labs(subtitle = Title, x = "log(X)", y = "log(Y)", color = "Color" ) +
theme_bw() + theme(legend.position = legend.position)
}

g1 <- graph(Title = "Vertical", color.by = cl_vert)
g2 <- graph(Title = "Horizontal", color.by = cl_hoz)
g3 <- graph(Title = "Center", color.by = cl_cent)

#Cowplot
legend <- get_legend(graph(color.by = cl_vert, legend.position = "right")) #Not a memory waste
plot <- plot_grid(g1, g2, g3, labels = c("A", "B", "C"))
title <- ggdraw() + draw_label(paste0("Data Ex ", "1"), fontface = 'bold')
plot2 <- plot_grid(title, plot, ncol=1, rel_heights=c(0.1, 1)) # rel_heights values control title margins
plot3 <- plot_grid(plot2, legend, rel_widths = c(1, 0.3))
plot3

#gridExtra
plot_grid.ex <- grid.arrange(g1, g2, g3, ncol = 2, top = paste0("Data Ex ", "1"))
plot_grid.ex

pryr 的内存使用情况

    #Comparison
object_size(plot_grid) #315 kB
object_size(plot3) #1.45 MB
#Individual objects
object_size(g1) #756 kB
object_size(g2) #756 kB
object_size(g3) #756 kB
object_size(g1, g2, g3) #888 kB
object_size(legend) #43.6 kB

其他问题:写完这个问题并提供示例数据后,我就想起了gridExtra,尝试了一下,它似乎比其组件图的组合数据占用更少的内存。我认为除了颜色分配之外,g1、g2 和 g3 共享相同的数据,这就是为什么各个组件和总对象大小之间存在大约 130 kB 差异的原因。为什么plot_grid 占用的空间比这还要少? ls.str(plot_grid) 似乎没有显示 g1、g2 和 g3 的任何合并。我最好的选择是使用 lineprof() 并逐行比较?

我浏览/阅读/咨询的来源:

请耐心等待,因为我是一名新程序员(12 月才真正开始编写脚本);我还不了解所有的技术细节,但我想了解。

最佳答案

如果您将数据转换为长格式,则分面将在此处起作用。这是一个例子:

library(tidyverse)

df %>% gather(method, cluster, cl_vert:cl_cent) %>%
ggplot(aes(x = x.points, y = y.points)) +
geom_point(aes(color = cluster)) +
scale_color_brewer(palette = "Set1") +
theme_bw() +
facet_wrap(~ method)

enter image description here

关于r - 具有共享数据的多个 ggplot2 图表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49928579/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com