如何使用geom_tile在ggplot2中创建相对磁贴大小?

5

我想要做一个关于颜色集合和它们的补色的可视化展示。我希望使用geom_tile将它们放在一起。问题是有些目标颜色有多个补色,所以我需要能够平均地将补色瓷砖分配给这些颜色。

我的测试数据集如下:

test_pair = data.frame(pair_number = c(1, 1, 2, 2, 3, 3, 3), 
                       color = c('#5f75e6', '#e6d05f', '#5f75e6', '#5fb9e6', '#5f75e6', '#b9e65f', '#e68d5f'),
                       group = c('target', 'comp', 'target', 'comp', 'target', 'comp', 'comp'),
                       bin_width = c(1, 1, 1, 1, 1, 0.5, 0.5))

以下为我的代码:

ggplot(test_pair, aes(x = factor(group), y = factor(pair_number), width = bin_width)) +
       geom_tile(aes(fill = color)) +
       scale_fill_identity() +
       scale_x_discrete('', expand = c(0, 0)) +
       scale_y_discrete('', expand = c(0, 0)) + 
       theme_bw() +
       theme(line = element_blank(),
            panel.grid.major = element_blank(),
            panel.grid.minor = element_blank(),
            panel.border = element_blank(),
            plot.background = element_rect(fill = '#c4a879'),
            axis.ticks = element_blank(),
            axis.text.y = element_text(size = 14),
            axis.text.x = element_text(size = 14),
            axis.title.y = element_text(color = hex))

图形确实将其中一种互补色分成了两半,但是将该瓷砖居中并未绘制第二个互补色。我希望图形能够将两种互补色并排打印,而不必像geom_tile文档中那样指定x轴的断点。有人知道如何做到这一点吗?
1个回答

5
两种颜色都在那里。只是两个瓷砖(颜色)的x和y坐标以及宽度相同,因此两个瓷砖(颜色)完全重叠。要查看这种情况,请调整底层颜色的宽度;例如,在您的test_pair数据框中更改bin_width行为:bin_width = c(1, 1, 1, 1, 1, 0.75, 0.5)),然后运行ggplot命令。
为了解决问题,请偏移两个瓷砖的x位置。一种方法是在x轴上使用数字刻度,然后在scale_x_continuous()中添加适当的断点和标签。但如何在不指定断点的情况下进行偏移?我不确定。
test_pair = data.frame(pair_number = c(1, 1, 2, 2, 3, 3, 3), 
                       color = c('#5f75e6', '#e6d05f', '#5f75e6', '#5fb9e6', '#5f75e6', '#b9e65f', '#e68d5f'),
                       group = c(2, 1, 2, 1, 2, .75, 1.25),
                       bin_width = c(1, 1, 1, 1, 1, .5, .5))

ggplot(test_pair, aes(x = group, y = factor(pair_number), width = bin_width)) +
       geom_tile(aes(fill = color)) +
       scale_fill_identity() +
       scale_x_continuous('', breaks = c(1,2), labels = c("comp", "target"), expand = c(0, 0)) +
       scale_y_discrete('', expand = c(0, 0)) + 
       theme_bw()

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接