gpt4 book ai didi

r - 为 ggplot 气泡图创建同心圆图例

转载 作者:行者123 更新时间:2023-12-01 23:10:23 30 4
gpt4 key购买 nike

我正在尝试重新创建 this visualization使用 ggplot2 绘制气泡图(我在 R 中找到了执行此操作的代码,但没有使用 ggplot2 包)。这是我到目前为止所拥有的。目前我的代码还存在一些其他错误,但我希望图例显示同心圆的大小,而不是按行显示的圆。感谢您的帮助!

原始可视化:
enter image description here

我的复制品:
enter image description here

我的(简化的)代码:

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))

最佳答案

这是一种我们从头开始构建想象的图例的方法。

1)这部分稍微调整您的基础图表​​。

感谢您提供源数据。我之前错过了这一点,并编辑了这个答案以使用它。我切换到不同的点形状,以便我们可以指定外部边框(颜色)以及内部填充。

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)

2)这里我制作了另一个表格用于同心图例圆

library(dplyr); library(ggplot2)
legend_bubbles <- data.frame(
label = c("3", "20", "40m"),
size = c(3E6, 20E6, 40E6)
) %>%
mutate(radius = sqrt(size / pi))

3) 此部分添加图例气泡、文本和标题。

这并不理想,因为不同的打印尺寸需要调整位置。但使用 ggplot_build 进入底层 grobs 来提取和使用这些大小调整似乎会变得很复杂......

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")

enter image description here

关于r - 为 ggplot 气泡图创建同心圆图例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52612867/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com