如何为facet_wrap(ed)geom_count图添加标签?

问题描述 投票:0回答:1

我正在使用facet_wrap创建一个刻面图。我希望文本标签包含在泡泡中。相反,似乎总数被包括为标签 - 即所有图表具有相同的数字但不同的气泡大小(这是正确的)。

(编辑)

我的代码:

Category1 <- c('A','B','C','A','B','C','A','B','C','A','B','C','A','B','C','A','B','C','A','B')
Category2 <- c('W','V','W','V','W','V','W','V','W','V','W','V','W','V','W','V','W','V','W','V')
Class <- c(1,2,3,4,1,2,3,4,1,2,3,4,1,2,3,4,1,2,3,4)

df <- data.frame(Category1, Category2, Class)


g <- ggplot(df, aes(Category1, Category2))

g <- g + facet_wrap(Class ~ ., nrow = 3) + geom_count(col="tomato3", show.legend=F) + scale_size_continuous(range = c(5, 10))
labs(subtitle="Count Plot", y="Category2", x="Category1", title="Cat1 vs Cat2")

g

g2 <-  g + geom_text(data=ggplot_build(g)$data[[1]], aes(x, y, label=n), size=2) #+ scale_size(range = c(5, 15))
g2

我希望气泡的大小将由气泡内的文字指示。但实际结果是所有图表都具有相同的数字。我希望小气泡的数量与它的大小成正比。

enter image description here

r ggplot2 facet-wrap
1个回答
1
投票

问题是使用ggplot_build数据的代码与原始数据的类别不同。您需要事先创建计数数据并将其用于绘图。

创建计数数据

library(tidyverse)
df_count <- df %>%
    count(Class, Category1, Category2)

情节

有两种方法可以合并这些新数据。

Method 1

我展示的第一个例子是使用dfdf_count。此方法将最低限度地修改您的代码:

g <- ggplot(df, aes(Category1, Category2))

g <- g + facet_wrap(Class ~ ., nrow = 3) + geom_count(col="tomato3", show.legend=F) + 
    geom_text(data = df_count, aes(Category1, Category2, label=n), size=2) + 
    scale_size_continuous(range = c(5, 10)) + 
    labs(subtitle="Count Plot", y="Category2", x="Category1", title="Cat1 vs Cat2")
g

添加了geom_text(data = df_count, aes(Category1, Category2, label=n), size=2) +行。

Method 2

此方法仅使用计数数据。它使用geom_point()而不是geom_count()并使用变量n改变大小。在代码可读性方面,这种方法可能更好。

g_alternative <- ggplot(df_count, aes(Category1, Category2,  label = n)) + 
    facet_wrap(Class ~ ., nrow = 3) + 
    geom_point(col="tomato3", aes(size = n),  show.legend=F) + 
    geom_text() + 
    scale_size_continuous(range = c(5, 10)) + 
    labs(subtitle="Count Plot", y="Category2", x="Category1", title="Cat1 vs Cat2")
g_alternative

输出如下所示:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.