Kri*_*sta 4 bubble-chart r legend ggplot2
我正在尝试使用ggplot2 重新创建气泡图的可视化效果(我已经找到了在R中执行此操作的代码,但没有使用ggplot2包进行此操作)。到目前为止,这就是我所拥有的。目前,我的代码还存在其他一些错误,但是我希望图例显示同心圆的大小,而不是行中显示的圆。谢谢你的帮助!
原始可视化:

我的复制品:

我的(简体)代码:
crime <-
read.csv("http://datasets.flowingdata.com/crimeRatesByState2005.tsv",
header=TRUE, sep="\t")
ggplot(crime,
mapping= aes(x=murder, y=burglary))+
geom_point(aes(size=population), color="red")+
geom_text(aes(label=state.name), show.legend=FALSE, size=3)+
theme(legend.position = c(0.9, 0.2))
Run Code Online (Sandbox Code Playgroud)
这是一种我们从头开始构建图例的方法。
感谢您包含源数据。我之前想念它,并编辑了此答案以使用它。我切换到其他点形状,以便我们既可以指定外部边界(颜色),也可以指定内部填充。
gg <- ggplot(crime,
mapping= aes(x=murder, y=burglary))+
geom_point(aes(size=population), shape = 21, color="white", fill = "red")+
ggrepel::geom_text_repel(aes(label = state.name),
size = 3, segment.color = NA,
point.padding = unit(0.1, "lines")) +
theme_classic() +
# This scales area to size (not radius), specifies max size, and hides legend
scale_size_area(max_size = 20, guide = FALSE)
Run Code Online (Sandbox Code Playgroud)
library(dplyr); library(ggplot2)
legend_bubbles <- data.frame(
label = c("3", "20", "40m"),
size = c(3E6, 20E6, 40E6)
) %>%
mutate(radius = sqrt(size / pi))
Run Code Online (Sandbox Code Playgroud)
这是不理想的,因为不同的打印尺寸将需要调整位置。但是使用ggplot_build进入底层grob似乎很复杂,以提取并使用这些大小调整...
gg + geom_point(data = legend_bubbles,
# The "radius/50" was trial and error. Better way?
aes(x = 8.5, y = 250 + radius/50, size = size),
shape = 21, color = "black", fill = NA) +
geom_text(data = legend_bubbles, size = 3,
aes(x = 8.5, y = 275 + 2 * radius/50, label = label)) +
annotate("text", x = 8.5, y = 450, label = "Population", fontface = "bold")
Run Code Online (Sandbox Code Playgroud)