如何在R语言中绘制存储在列表内的概率值数据
解决方案
报错原因
你直接对LIST1调用plot()报错不是画布尺寸的问题,是因为LIST1为嵌套列表结构,基础绘图函数无法直接识别该存储格式,会尝试将每个列表元素作为独立绘图对象渲染,最终超出默认边距阈值。
数据格式转换
首先将嵌套列表转换为适合绘图的长格式数据框,可根据你使用的存储列表二选一:
基于LIST1转换
library(tidyverse) plot_df <- purrr::imap_dfr(LIST1, ~{ name_seg <- stringr::str_split(.y, "_", simplify = TRUE) tibble( iter = as.integer(name_seg[1]), time_step = as.integer(name_seg[2]), class = factor(1:nrow(.x)), prob = as.numeric(.x[,1]) ) })
基于LIST2转换
plot_df <- expand.grid(iter = 1:16, time_step = 1:2) %>% dplyr::rowwise() %>% dplyr::mutate(prob = list(LIST2[[iter, time_step]][,1])) %>% tidyr::unnest_longer(prob, indices_to = "class") %>% dplyr::mutate(class = factor(class))
绘图实现
以下代码可生成你需要的迭代概率变化图,和参考的Matlab图效果一致:
ggplot(plot_df, aes(x = iter, y = prob, color = class, group = class)) + geom_line(linewidth = 1) + geom_point(size = 2) + # 按时间步分2行展示 facet_wrap(~time_step, nrow = 2, labeller = labeller(time_step = ~paste0("时间步", .x))) + scale_x_continuous(breaks = 1:16, name = "迭代次数") + scale_y_continuous(limits = c(0, 1), name = "近似后验概率") + theme_bw() + theme( legend.position = "top", panel.grid.minor = element_blank() )
如果需要堆叠面积展示概率分布,把geom_line和geom_point替换为geom_area(position = "stack", alpha = 0.7)即可。
边距问题兜底处理
如果仍出现边距相关报错,先重置绘图设备再手动调整边距参数:
# 重置当前绘图设备 dev.off() # ggplot2绘图时额外添加边距设置 last_plot() + theme(plot.margin = unit(c(1,1,1,1), "cm"))
内容的提问来源于stack exchange,提问作者Steffen Schwerdtfeger
相关产品推荐
相关产品推荐

