我正在使用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
我希望气泡的大小将由气泡内的文字指示。但实际结果是所有图表都具有相同的数字。我希望小气泡的数量与它的大小成正比。
问题是使用ggplot_build
数据的代码与原始数据的类别不同。您需要事先创建计数数据并将其用于绘图。
library(tidyverse)
df_count <- df %>%
count(Class, Category1, Category2)
有两种方法可以合并这些新数据。
我展示的第一个例子是使用df
和df_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) +
行。
此方法仅使用计数数据。它使用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
输出如下所示: