gpt4 book ai didi

r - 在冲积图中设置颜色和标题

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

我有一个简单的 data.frame,使用 alluvial 包将其制作成简单的冲积图。我如何编辑情节?我的问题按重要性排序是:

  1. 更改配色方案,以便来自相同颜色的流量“录取”单位颜色相同。
  2. 添加标题
  3. 保存此图,以便稍后我可以将其绘制到带有一些 ggplot 的网格中

警告:ggalluvial 可能更容易,但不幸的是我无法在工作中安装它,因此解决方案需要使用基本 r、ggplot 或 alluvial 包。

library(alluvial)
df <- structure(list(Admitted.To =
c("UnitC", "UnitC", "UnitC", "UnitC", "UnitD", "UnitD",
"UnitD", "UnitD", "UnitE", "UnitE", "UnitE", "UnitF",
"UnitB", "UnitB", "UnitB", "UnitB", "UnitB", "UnitG",
"UnitH", "UnitA", "UnitA", "UnitA", "UnitA", "UnitA"),
Discharged.From = c("UnitC", "UnitD", "UnitE", "UnitA",
"UnitC", "UnitD", "UnitE", "UnitA",
"UnitD", "UnitE", "UnitA", "UnitF",
"UnitD", "UnitI", "UnitE", "UnitB",
"UnitA", "UnitG", "UnitH", "UnitC",
"UnitD", "UnitI", "UnitE", "UnitA"),
n = c(136, 2, 1, 2, 1, 162, 2, 3, 1, 213, 1, 3, 5, 1, 7,
22, 23, 1, 32, 10, 9, 39, 9, 607)),
.Names = c("Admitted.To", "Discharged.From", "n"),
row.names = c(NA, -24L),
class = c("tbl_df", "tbl", "data.frame"))

我一直在使用下面的颜色代码,直到弄清楚如何将颜色映射到“已录取”组

set.seed(8) # for nice colors
cols <- hsv(h = sample(1:8/10), s = sample(3:8)/8, v = sample(3:8)/8)

还有我的冲积图代码:

alluvial(df[,1:2], 
freq = 8,
blocks = T,
col = cols)

我尝试将 title = "SampleTitleHere" 添加到我的代码中,但它只是绘制了另一列。我没有找到太多关于这个包的文档。

最佳答案

感谢您使用冲积包。一一解答您的问题:

1 Change the color scheme so that flows coming from the same "Admitted.To" unit are the same color.

例如像这样


pal <- RColorBrewer::brewer.pal(8, "Set1") # colors to use
alluvial(
f[,1:2],
freq = 8,
blocks = T,
col = k[ match(f$Admitted.To, unique(f$Admitted.To)) ]
)
  1. Add a title

也许我们会添加一个 titlemain 参数。同时使用mtext()在顶部添加“边距文本”


pal <- RColorBrewer::brewer.pal(8, "Set1")
alluvial(
f[,1:2],
freq = 8,
blocks = T,
col = k[ match(f$Admitted.To, unique(f$Admitted.To)) ]
)
mtext("A title", 3, line=3, font=2)

如果您的标题跨越多行,或者您希望标题和绘图之间有更大的边距或空间,您可以 (a) 通过使用传递的向量的第三个元素的较大数量来增大边距到 mar 参数; (b) 修改 mtext()line 参数来调整标题应该出现在离绘图多远的位置。

  1. Save this plot so I can later plot it into a grid with a few ggplots

对此我没有快速的答案。如果您需要将其与其他基于 ggplot 的图形混合,使用 ggalluvial 会是更好的选择。请参阅下文,了解如何让它发挥作用。

Caveat: ggalluvial might be easier but unfortunately I can't install it at work, so the solution needs to use base r, ggplot, or the alluvial package.

即使您不是系统管理员,您也应该能够安装和使用任何 R 软件包(例如 ggalluvial)。您只需将它们安装在您有权写入文件的地方即可。这甚至可以是您保存分析的文件夹。参见例如https://csg.sph.umich.edu/docs/R/localpackages.htmlhttp://www.stat.osu.edu/computer-support/mathstatistics-packages/installing-r-libraries-locally-your-home-directory ,或 Google 搜索“R 用户库树”。

关于r - 在冲积图中设置颜色和标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43130418/

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