我想在下面复制此图表。我已经达到了一个阶段,我可以使用plot_ly重现R中的条形图。但是,我宁愿在辅助轴上添加线段。那么,有人可以帮助我在我的图表代码中添加的内容,以获得类似的轴。我有详细信息和下面的MWE。
我正在尝试使用plot_ly。这是我的数据框架和我做的:
# 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')
答案 0 :(得分:1)
您可以通过添加type='scatter'
和mode='lines'
的其他跟踪(我将其命名为life.cycle
)并在layout(...)
中设置其他y轴来实现此目的:
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))
答案 1 :(得分:0)
您只需在当前的地块上添加额外的一条线。像下面这样的东西会起作用。 ay
提供了可以根据您的要求修改的布局详细信息。
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')