关于 r:plotly 与多个系列

plotly with multiple series

我想在下面复制这个图表。我已经到了可以使用 plot_ly 在 R 中重现条形图的阶段。但是,我宁愿没有在辅助轴上添加线段。那么,有人可以帮我在图表代码中添加什么,以获得类似的轴。我在下面有详细信息和 MWE。

enter

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# download data  
if (!file.exists("SCFP2013.xlsx")) {
  download.file("https://www.federalreserve.gov/econres/files/scfp2013excel.zip","SCFP2013.zip")
  unzip("scfp2013.zip")
}

df <- read_excel("SCFP2013.xlsx")
df[df$NETWORTH < 0, ]$NETWORTH <- 0 # if net worth is less than 0, assign a value of zero

# compute values of retirmet assets
households2 <- data.frame(
  netWorth = df$NETWORTH,
  weight = df$WGT,
  RETQLIQ = df$RETQLIQ    
)

# group households into segments
households2 <- households2[households2$netWorth >= 10000, ]

# split into net worth segments
nw2 <- floor(log10(households2$netWorth))
segment2 <- ifelse(nw2 == 4,"     $10k",
                   ifelse(nw2 == 5,"    $100K",
                          ifelse(nw2 == 6,"   $1M",              
                                 ifelse(nw2 == 7,"  $10M",              
                                        ifelse(nw2 == 8," $100M",              
                                              "$1B+")))))

# compute average asset distrubtions
results2            <- as.data.frame((aggregate(households2,list(segment2),mean)))
results2$life.cycle <- results2$RETQLIQ/results2$netWorth

plot_ly(results2, x = ~Group.1, y = ~RETQLIQ, type = 'bar', name = 'Retirement (Pension/IRA)') %>%
  layout(yaxis = list(title = 'Millions'), xaxis = list(title ="Net Worth"),
         title ="Pensions Wealth", barmode = 'stack')

您可以通过添加另一个带有 type='scatter'mode='lines' 的轨迹(我将其命名为 life.cycle)并在 layout(...):

中设置一个额外的 y 轴来实现此目的

1
2
3
4
5
6
7
8
9
10
11
12
plot_ly(results2, x = ~Group.1, y = ~RETQLIQ,
       type = 'bar', name = 'Retirement (Pension/IRA)') %>%

add_trace(x = ~Group.1, y = ~life.cycle,
          type = 'scatter', mode = 'lines', name = 'life.cycle',
          yaxis = 'y2', line = list(color = 'orange')) %>%

  layout(title ="Pensions Wealth", barmode = 'stack',
         xaxis = list(title ="Net Worth"),
         yaxis = list(side="left", title = 'Millions'),
         yaxis2 = list(side = 'right', overlaying ="y", title = '',
         showgrid = FALSE, zeroline = FALSE))

enter

1
2
3
4
5
6
7
8
9
10
11
ay <- list(
  tickfont = list(color ="red"),
  overlaying ="y",
  side ="right",
  title =""
)

plot_ly(results2, x = ~Group.1, y = ~RETQLIQ, type = 'bar', name = 'Retirement (Pension/IRA)') %>%
  add_lines(x = ~Group.1, y = ~life.cycle, name ="Life Cycle", yaxis ="y2") %>%
  layout(yaxis = list(title = 'Millions'), xaxis = list(title ="Net Worth"), yaxis2 = ay,
         title ="Pensions Wealth", barmode = 'stack')