如何用R中的气泡图绘制比例数据

时间:2019-02-11 20:47:56

标签: r ggplot2 bubble-chart

我有两个不同年份的鱼类饮食比例数据。我正在努力使气泡大小反映出可能值的范围是0-1,但实际上没有值达到1。这是我在SigmaPlot中制作的图形,我想在R中重新创建。 12种不同的猎物类别。

enter image description here

我设法在R中创建了一个图,但是大小似乎已缩放到最大比例。这是代码和复制的图。

library(reshape)
library(ggplot2)

Species <- as.character(c(1:12))
yr2016 <- as.numeric(c(0.17, 0.011, 0.022, 0.003, 0.51, 0.1, 
                       0.01, 0.03, 0.004, 0.06, 0.07, 0.01))
yr2017 <- as.numeric(c(0.197, 0.005, 0.027, 0.01, 0.337, 0.157,
                       0.008, 0.038, 0.017, 0.17, 0.032, 0.002))
data <- as.data.frame(cbind(Species, yr2016, yr2017))
data$yr2016 <- as.numeric(as.character(data$yr2016))
data$yr2017 <- as.numeric(as.character(data$yr2017))
data2 <- melt(data)

ggplot(data2,
       aes(x = variable, y = factor(Species, levels = unique(Species))))+
  geom_point(aes(size = value))+
  labs(y = "Prey Items", x = "Year")+
  theme_classic() +
  scale_size_area()

enter image description here

1 个答案:

答案 0 :(得分:0)

您可以使用参数scale_size_arealimits = c(0,1)内手动设置限制,并使用max_size参数即max_size = 20

希望这能为您提供所需的东西。

    library(reshape)
    library(ggplot2)
    library(data.table)
    Species <- as.character(c(1:12))
    yr2016 <-as.numeric(c(0.17,0.011,0.022,0.003,0.51,0.1,0.01,0.03,0.004,0.06,0.07,0.01))
    yr2017 <-as.numeric(c(0.197,0.005,0.027,0.01,0.337,0.157,0.008,0.038,0.017,0.17,0.032,0.002))
    data<-as.data.frame(cbind(Species,yr2016,yr2017))
    data$yr2016 <- as.numeric(as.character(data$yr2016)); 
    data$yr2017 <- as.numeric(as.character(data$yr2017))
    data2<-melt(data)
    p <-  ggplot2::ggplot(data2,aes(x=variable, y=factor(Species, levels=unique(Species))))+
      geom_point(aes(size=value))+
      labs(y="Prey Items",x="Year")+
      theme_classic() +
      scale_size_area( limits = c(0,1),max_size = 20)
    p

enter image description here

如果需要,您还可以添加自己的breaks,例如c(0.1, 0.2, 0.5, etc) 或进行一系列的中断:seq(from = 0.1, to = max(data2$value), by = 0.1)

如果您不仅要设置最大大小,还要设置最小大小,则可以切换到scale_size而不是scale_size_area,其中range(min,max)设置两端的大小规模

library(reshape)
library(ggplot2)
library(data.table)
Species <- as.character(c(1:12))
yr2016 <-as.numeric(c(0.17,0.011,0.022,0.003,0.51,0.1,0.01,0.03,0.004,0.06,0.07,0.01))
yr2017 <-as.numeric(c(0.197,0.005,0.027,0.01,0.337,0.157,0.008,0.038,0.017,0.17,0.032,0.002))
data<-as.data.frame(cbind(Species,yr2016,yr2017))
data$yr2016 <- as.numeric(as.character(data$yr2016)); 
data$yr2017 <- as.numeric(as.character(data$yr2017))
data2<-melt(data, id = 'Species')
sizes <- c('0.2' = 0.2, '0.4' = 0.4, '0.6' = 0.6, '0.8'= 0.8, '1.0' = 1.0)
p <-  ggplot2::ggplot(data2,aes(x=variable, y=factor(Species, levels=unique(Species))))+
  geom_point(aes(size=value))+
  labs(y="Prey Items",x="Year")+
  theme_classic() +
  scale_size( limits = c(0,1),breaks = seq(from = 0.1, to = max(data2$value), by = 0.1),range = c(1,20))
p

enter image description here