gpt4 book ai didi

r - ggplot2:汇总行和列的独立连续填充

转载 作者:行者123 更新时间:2023-12-04 12:50:46 31 4
gpt4 key购买 nike

我正在使用一种策略,使用 geom_tile 在热图中绘制汇总(总计)行,这涉及在 data_frame 中为行和列总计创建额外的行:

library(dplyr)
library(ggplot2)

entitites = LETTERS[1:10]
# create some sample data
df_foo = bind_cols(
data_frame(Group1 = rep(c("A", "B"), each = 100)),
bind_rows(
expand.grid(
Left = entitites, Right = entitites,
stringsAsFactors = FALSE
),
expand.grid(
Left = entitites, Right = entitites,
stringsAsFactors = FALSE
)
),
data_frame(Value = rpois(200, 15))
)

# create the summary row & column
df_foo_aug = bind_rows(
df_foo,
df_foo %>%
group_by(Left, Group1) %>%
summarize(
Value = sum(Value),
Right = "Total"
),
df_foo %>%
group_by(Right, Group1) %>%
summarize(
Value = sum(Value),
Left = "Total"
)
)

# create the plot
df_foo_aug %>%
ggplot(aes(x = Right, y = Left, fill = Value)) +
geom_tile() +
facet_wrap(~ Group1) +
theme_bw()

这产生:

enter image description here

显然,总计行/列需要自己的填充渐变,但不清楚如何(如果)我可以添加第二个连续/渐变填充。

实现相同预期结果的任何其他方式也可以作为该问题的解决方案。

最佳答案

这里的问题是,在ggplot中,原则上,一种美学只能有一个尺度。所以 fill 只能有一个刻度。但是,有一些方法可以避免这种情况,例如使用 color 作为第二个比例。或者,根据 shayaa's comment,您可以乱用 grobs 来完成工作。 .

下面是一些可能的例子,使用geom_point来显示总数:

base_plot <-  
ggplot(df_foo_aug, aes(x = Right, y = Left)) +
geom_tile(data = filter(df_foo_aug, Right != 'Total', Left != 'Total'),
aes(fill = Value)) +
coord_equal() +
facet_wrap(~ Group1) +
scale_y_discrete(limits = rev(sort(unique(df_foo_aug$Left)))) +
theme_classic() + theme(strip.background = element_blank())

一个相当标准的方法:

base_plot +
geom_point(data = filter(df_foo_aug, Right == 'Total' | Left == 'Total'),
aes(col = Value), size = 9.2, shape = 15) +
scale_color_gradient('Total', low = 'black', high = 'red')

enter image description here

使用具有更宽感知范围的色标:

base_plot +
geom_point(data = filter(df_foo_aug, Right == 'Total' | Left == 'Total'),
aes(col = Value), size = 9.2, shape = 15) +
viridis::scale_fill_viridis(option = 'B') +
viridis::scale_color_viridis('Total', option = 'D')

enter image description here

还将 size 映射到总的 Value:

base_plot +
geom_point(data = filter(df_foo_aug, Right == 'Total' | Left == 'Total'),
aes(col = Value, size = Value)) +
scale_size_area(max_size = 8, guide = 'none') +
viridis::scale_fill_viridis(option = 'B') +
viridis::scale_color_viridis('Total', option = 'D')

enter image description here

就我个人而言,我非常喜欢最后一个。

最后一项改进是将 y 轴向上移动,对此我推荐 cowplot package .

关于r - ggplot2:汇总行和列的独立连续填充,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39116838/

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