R语言 如何在分组直方图图中添加整体直方图

jaxagkaj  于 2023-06-19  发布在  其他
关注(0)|答案(1)|浏览(110)

我有一个dataset,它有多个列,其中一个是分类变量。分类变量取3个值:1,2,3.我想在ggplot中创建一个图,其中有3个直方图,一个在另一个下面,然后我想在第三个直方图下面添加直方图,其中我们不考虑分类变量。到目前为止,我已经写了下面的代码

#The name of the dataset is dataset.clust

dataset.clust$cluster = factor(dataset.clust$cluster)

library(patchwork)
library(ggplot2

dataset.clust$cluster = factor(dataset.clust$cluster)

hist_plot1 = ggplot(dataset.clust, aes(x = population, fill = cluster)) +
  geom_histogram(position = "identity", alpha = 0.7) +
  facet_wrap(~ cluster, nrow = 3) +
  scale_fill_manual(values = c("red", "green", "blue")) +
  guides(fill = guide_legend(title = "Cluster")) +
  ggtitle("Grouped Histograms for population")

# Second Histogram
hist_plot2 = ggplot(dataset.clust, aes(x = population)) +
  geom_histogram(fill = "yellow", color = "black")

# Combine histograms and arrange vertically
combined_plot = hist_plot1 / hist_plot2

print(combined_plot)

上面的代码给出了this

有人知道如何将这些图合并成一个图,使四个图具有相同的x和y轴?

4nkexdtk

4nkexdtk1#

一种方法是

  • 首先将一个(尚未使用的)水平“A-C”添加到因子“聚类”
  • 添加一个geom_histogram及其自己的数据集,该数据集是所有观测的聚类设置为“A-C”的原始数据

示例:

d <- data.frame(cluster = gl(3, 100, labels = c(LETTERS[1:3], 'A-C')),
                value = rnorm(300)
                )

d |>
ggplot(aes(value, fill = cluster)) +
    geom_histogram() +
    geom_histogram(data = d |> mutate(cluster = gl(1, 300, labels = c('A-C')))) +
    facet_wrap(~ cluster, ncol = 1) +
    scale_fill_discrete(breaks = c(LETTERS[1:3], 'A-C'),
                        name = 'redundant use\nof colour'
                        )

相关问题