如何避免气泡图中的气泡重叠?

时间:2020-02-28 00:32:27

标签: r ggplot2 scatter-plot bubble-chart

我想像右图一样在气泡图中分别绘制数据(我在PowerPoint中这样做只是为了可视化)。 enter image description here 目前,我只能创建一个类似于气泡重叠的左侧的图。如何在R中执行此操作?

b <- ggplot(df, aes(x = Year, y = Type))

b + geom_point(aes(color = Spp, size = value), alpha = 0.6) +
  scale_color_manual(values = c("#0000FF", "#DAA520",  "#228B22","#E7B888")) +
  scale_size(range = c(0.5, 12)) 

1 个答案:

答案 0 :(得分:4)

您可以在position_dodge()中使用geom_point参数。如果直接将其应用于代码,它将以水平方式定位点,因此,其想法是切换x和y变量并使用coord_flip以正确的方式获得它:

library(ggplot2)
ggplot(df, aes(y = as.factor(Year), x = Type))+ 
  geom_point(aes(color = Group, size = Value), alpha = 0.6, position = position_dodge(0.9)) +
  scale_color_manual(values = c("#0000FF", "#DAA520",  "#228B22","#E7B888")) +
  scale_size(range = c(1, 15)) +
  coord_flip()

enter image description here

看起来您要达到什么目标?


编辑:在每个点的中间添加文本

要在每个点上添加标签,可以使用geom_text并设置与position_dodge2相同的geom_point参数。

注意:我使用position_dodge2而不是position_dodge并略微改变了width的值,因为我发现position_dodge2更适合这种情况。

library(ggplot2)
ggplot(df, aes(y = as.factor(Year), x = Type))+ 
  geom_point(aes(color = Group, size = Value), alpha = 0.6, 
             position = position_dodge2(width  = 1)) +
  scale_color_manual(values = c("#0000FF", "#DAA520",  "#228B22","#E7B888")) +
  scale_size(range = c(3, 15)) +
  coord_flip()+
  geom_text(aes(label = Value, group = Group), 
            position = position_dodge2(width = 1))

enter image description here

可复制的示例

由于您没有提供可复制的示例,因此我提出了一个可能无法完全代表原始数据集的示例。如果我的回答对您没有帮助,您应该考虑提供一个可重复的示例(请参见此处:How to make a great R reproducible example

Group <- c(LETTERS[1:3],"A",LETTERS[1:2],LETTERS[1:3])
Year <- c(rep(1918,4),rep(2018,5))
Type <- c(rep("PP",3),"QQ","PP","PP","QQ","QQ","QQ")
Value <- sample(1:50,9)
df <- data.frame(Group, Year, Value, Type)
df$Type <- factor(df$Type, levels = c("PP","QQ"))