【发布时间】:2021-05-07 15:55:48
【问题描述】:
我正在为以下数据框使用三个系列绘制条形图:
library(plotly)
library(dplyr)
groups = c("high","low")
A1 = runif(2, min = 0, max = 1)
A2 = runif(2, min = 0, max = 1)
B1 = runif(2, min = 0, max = 1)
B2 = runif(2, min = 0, max = 1)
C1 = runif(2, min = 0, max = 1)
C2 = runif(2, min = 0, max = 1)
dfPlot = data.frame(groups, A1, A2,B1, B2,C1, C2 )
必须将 A2、B2 和 C2 绘制为基准数据。我使用下面的代码以条形图绘制 A1、B1 和 C1,然后将基准绘制为覆盖条形图。我还尝试将基准值绘制为点,但看起来不太好。
chrt_title <- list(
family = "Arial",
size = 14,
color ="#555555")
ax <- list(
title = "",
zeroline = FALSE,
showline = FALSE,
showticklabels = FALSE,
showgrid = FALSE
)
tit<-function(txt) {
jt<- list(
text = txt,
font = chrt_title,
xref = "paper",
yref = "paper",
yanchor = "bottom",
xanchor = "center",
align = "center",
x = 0.5,
y = 0,
showarrow = FALSE, yshift=-30
)
return(jt)
}
cl<-c("#33C9FF", "#3385FF")
k<-plot_ly(x = dfPlot [,1],
y = dfPlot [,2],
type = 'bar', name = "Total", marker=list(color=cl))
k<-k %>%
add_trace(x = dfPlot[,1],
y = dfPlot[,3],
type = 'bar', width = 0.3, name = "Benchmark",marker=list(color="#FFAB33"))
k<-k %>% layout(xaxis = ax,barmode = 'overlay', showlegend=TRUE, annotations=tit("AA"), bargap=0.01)
j<-plot_ly(x = dfPlot [,1],
y = dfPlot [,4],
type = 'bar', name = "Total", marker=list(color=cl))
j<-j %>%
add_trace(x = dfPlot[,1],
y = dfPlot[,5],
type = 'bar', width = 0.3, name = "Benchmark",marker=list(color="#FFAB33"))
j<-j %>% layout(xaxis = ax,barmode = 'overlay', showlegend=FALSE, annotations=tit("BB"), bargap=0.01)
m<-plot_ly(x = dfPlot [,1],
y = dfPlot [,6],
type = 'bar', name = "Total", marker=list(color=cl))
m<-m %>%
add_trace(x = dfPlot[,1],
y = dfPlot[,7],
type = 'bar', width = 0.3, name = "Benchmark",marker=list(color="#FFAB33"))
m<-m %>% layout(xaxis = ax,barmode = 'overlay', showlegend=FALSE, annotations=tit("CC") , bargap=0.01)
all<-subplot(k,j,m, nrows=1, shareY = TRUE,margin = 0.008 )
all<-all%>% layout( legend = list(orientation = "h",
xanchor = "center",
x = 0.5, y = 7), showlegend=TRUE)
all
叠加条形图的问题是图例不正确。条形图中有三种颜色,所以我需要三个图例,在这张图表中,图例是重复的。 如果更正带有此代码的图例,或者基准可以以不同的方式显示为带有图例的点,我的问题将得到解决。
提前感谢所有建议!
【问题讨论】: