我对 rplotly 很陌生,并创建了一个条形图,显示残疾人按年份分组的收入来源。现在我尝试添加散点跟踪来显示与非残疾人标记的比较,但标记未正确对齐,它们在 x 轴类别上居中对齐,而不是像条形图那样按年份变量分组。通过谷歌搜索,我发现github上也有人有同样的问题,但没有看到解决方案。有没有一种简单的方法可以使散点迹线的标记按年份变量对齐,以便它们与条形对齐?
我需要在 html 报告中生成 7 个图表,因此希望得到一些帮助。
此图表的我的数据:
structure(list(Disability = c("Disabled", "Disabled", "Disabled"
), Year = c("2017/18", "2018/19", "2019/20"), `Wages and salaries` = c(0.32,
0.34, 0.37), `All Pensions` = c(0.34, 0.32, 0.31), `All Social Security benefits` = c(0.37,
0.27, 0.23), `Self employment income` = c(0.03, 0.03, 0.06)), class = c("tbl_df",
"tbl", "data.frame"), row.names = c(NA, -3L))
这是我当前的代码块。
library(plotly)
Figure16 <- pivot_longer(Figure16, cols=c('Wages and salaries','All Pensions','All Social Security benefits','Self employment income'), names_to='Sources', values_to='Rate')
Figure16$`Rate` <- as.numeric(as.character(Figure16$`Rate`)) * 100
#wrapping labels on chart
Figure16$wrappedy <- sapply(Figure16$Sources,
FUN = function(Sources) {paste(strwrap(Sources, width = 25), collapse = " <br> ")})
Figure_16 <- plot_ly(Figure16[Figure16$Disability =="Disabled",],
x = ~wrappedy,
y = ~Rate,
type = 'bar',
color = ~Year,
colors = c("#8FAADC","#2F5597","#203864"),
name = ~Year,
#change colours depending on grouping
marker = list(color = ifelse(Figure16$Year=="2017/18","#8FAADC",
ifelse(Figure16$Year=="2018/19","#2F5597",
ifelse(Figure16$Year=="2019/20","#203864",
""))),
pattern = list(shape = ifelse(Figure16$Year=="2017/18","x",
ifelse(Figure16$Year=="2018/19","/",
""))),
line = list(color = ifelse(Figure16$Year=="2017/18","#8FAADC",
ifelse(Figure16$Year=="2018/19","#2F5597",
ifelse(Figure16$Year=="2019/20","#203864",
""))), width = 1.25))
)%>%
#adding line markers for comparison group
add_trace(Figure16[Figure16$Disability =="Non-disabled",], x = ~wrappedy, y = ~Rate, type = 'scatter', mode = 'markers', name = 'Non-disabled', marker = list(size = 30, symbol ='line-ew-open', color = "#FFC000",line=list(color = "#FFC000"), width = 33))%>%
#Making the yaxis start at zero and placing vertical line on chart
layout(yaxis = list(rangemode='tozero',ticksuffix = "%"))
#remove modebar as it overlaps with title
config(Figure_16, displayModeBar = FALSE)%>% layout(
xaxis = list(title = ""),
yaxis = list(title = "")
) %>%
#Making the xaxis start at zero
layout(yaxis = list(rangemode='tozero'))