气泡图表与气泡代表绝对大小

时间:2018-01-03 21:24:32

标签: r ggplot2 plotly

我正在尝试制作一个气泡图,其中每种颜色代表不同的珊瑚物种代码,气泡的大小代表一个人的大小,以米为单位,但也缩放到x或y轴,这是也以米为单位。

我还想为R中当前使用plotly的个人的大小添加一个额外的图例,但是可以使用R或Python中的其他模块。

我已经能够相对容易地获得物种的颜色,但我正在努力按尺寸缩放气泡。有没有人以前做过这个或知道任何作弊让它发挥作用?

     #Example Data
     Species <- c('SSID','PAST','CNAT','SSID','MMEA','PAST')
     Dist <- c(7.1,4.0,6.4,8.0,8.1,8.9)
     XDist <- runif(6, 0.0, 1.0)
     Transect <- c(1,2,1,1,3,2)
     Width <- c(10,15,100,45,60,27)
     Data <- data.frame(Transect, Species, Dist, XDist, Width)
     XDist <- Data$Transect - 1
     Data$XDist <- Data$XDist + XDist

    library(plotly)

    k <- plot_ly(Data, x = ~XDist, y = ~Dist, type = 'scatter', mode = 
     'markers',
         size = ~Width ,marker = list(sizemode = 'diameter', opacity = 1,
         symbol = ifelse(data$Disease == 'Y', "circle-open", "circle"),
         line = list(width = 5)),
         color = ~Species, colors = 'Set1',
         hoverinfo = 'text',
         text = ~paste('Width:', Width, '<br>Species:', Species)
         ) %>%
     layout(title = 'Coral',
       xaxis = list(showgrid = FALSE),
       yaxis = list(showgrid = FALSE))

Coral Map

1 个答案:

答案 0 :(得分:7)

经过深思熟虑并找到一对卡钳,我想我已经回答了自己的问题。假设宽度= 1000且高度= 1000,我的图上100厘米= 3.72毫米。 Plotly似乎根据最大气泡和最小气泡的大小来缩放气泡。默认尺寸上最大的气泡为2.45mm,最小气泡为0.21 mm。您可以使用这些测量值创建比率,将气泡绝对缩放到距离。

    #Data
    Species <- c('SSID','PAST','CNAT','SSID','MMEA','PAST')
    Coral <- c(1,2,3,4,5,6)
    Dist <- c(1,2.4,4.6,3.2,1.2,4.1)
    XDist <- c(2,3,0.5,2.3,4.1,2.5)
    Transect <- c(1,2,1,1,3,2)
    Width <- c(10,15,100,45,60,27)
    Disease <- c(0,0,0,1,0,0)
    Data <- data.frame(Coral, Transect, Species, Dist, XDist, Width, Disease)        

    Datamax <- (((max(Data$Width, na.rm = T)*3.72)/100)/2.45)*100
    Datamin <- (((min(Data$Width, na.rm = T)*3.72)/100)/0.21)*10
    k <- plot_ly(Data, x = ~XDist, y = ~Dist, type = 'scatter',
         mode ='markers',
         size = ~Width ,marker = list(sizemode = 'diameter', opacity = 0.75,
         symbol = ifelse(Data$Disease == 1, "circle-open", "circle"),
         line = list(width = 10)),
         color = ~Species, colors = 'Set1',
         hoverinfo = 'text',
         text = ~paste('Width:', Width, '<br>Species:', Species),
         width = 1000,
         height = 1000,# ) %>%
         sizes = c(Datamin,Datamax)) %>%

    add_annotations(text = Data$Coral,        
         xanchor = 'center', showarrow = F) %>%
    layout(title = 'Coral',
         xaxis = list(showgrid = TRUE,
             range = c(-0.25,5.25),
             zeroline = T,
             showline = T,
             mirror = "ticks",
             gridcolor = toRGB("grey50"),
             gridwidth = 2),
         yaxis = list(showgrid = FALSE,
             scaleanchor = "x",
             rangemode = "nonnegative"))
    k
    export(k,file = "Test.CoralMap.png")

Test Coral Map