[英]How to customize barchart in plotly R?
在条形图上:“销售”和“分享”变量通过条形图显示,而“成本”则通过红线显示。 现在我想删除/删除这条红线,只将数字保留在框中,并在图例图中添加相应的变量。 此外,我想将“分享”的平均值添加为 Y 轴上的水平线
df <- data.frame (model = c("A", "B", "C","D","E","F"),
share = c(12,20,15,9,60,20),
sale = c(16,25,18,14,67,28),
cost = c(14,19,28,24,57,28))
#set levels of model by cost
df$model <- factor(df$model, levels = arrange(df, desc(df$cost))$model)
library(tidyverse)
df_long <- df %>%
pivot_longer(
cols = -model
)
df_long %>%
filter(name != "cost") %>%
plot_ly(x = ~model, y = ~value, color = ~name, type = "bar",
customdata = ~name, colors = c("blue", "gray"),
hovertemplate = paste0("Model: %{x}<br>Value: %{y}<br>",
"Name: %{customdata}<extra></extra>")) %>%
add_lines(inherit = F, data = df, x = ~model,
y = ~cost, color = I("red"),
name = "cost",
hovertemplate = paste0("Model: %{x}<br>Value: %{y}<br>",
"Name: cost<extra></extra>")) %>%
add_annotations(data = df, x = ~model, y = ~cost, text = ~cost,
bgcolor = "white", bordercolor = "black",
xshift = 15, yshift = 15, showarrow = F) %>%
layout(barmode = "group")
实际上,这比您想象的要容易得多。 代替颜色的I('red')
,可以将其更改为I('transparent')
。 现在按成本计算的盒子看起来有点令人讨厌。 如果它看起来像出售和分享旁边的盒子可能会更好。
至于水平线,我已经添加了它。 我不知道你是否想给它贴上标签,一种特定的颜色……只是你想要这条线。 这就是我添加的内容。 我选择使用红色,因为它很突出。
df_long %>%
filter(name != "cost") %>%
plot_ly(x = ~model, y = ~value, color = ~name, type = "bar",
customdata = ~name, colors = c("blue", "gray"),
hovertemplate = paste0("Model: %{x}<br>Value: %{y}<br>",
"Name: %{customdata}<extra></extra>")) %>%
add_lines(inherit = F, data = df, x = ~model,
y = ~cost, color = I("transparent"),
name = "cost",
hovertemplate = paste0("Model: %{x}<br>Value: %{y}<br>",
"Name: cost<extra></extra>")) %>%
add_annotations(data = df, x = ~model, y = ~cost, text = ~cost,
bgcolor = "white", bordercolor = "black",
xshift = 15, yshift = 15, showarrow = F) %>%
layout(barmode = "group",
shapes = list(type = "line", x0 = 0, x1 = 1, xref = "paper",
y0 = mean(df$share), y1 = mean(df$share),
line = list(color = "red"),
name = "Average Share")) -> pL
or = ("function(el){
costLeg = el.querySelectorAll('g.traces')[2]; /* third legend entry */
costLC = costLeg.lastChild.cloneNode(true); /* copy the current rect element */
costLC.removeAttribute('pointer-events'); /* remove the pointer events */
costLeg.removeAttribute('class'); /*stop refresh from changing it*/
costLC.setAttribute('x', 15); /* starting point of box */
costLC.setAttribute('y', -5); /* 12 from middle; account for stroke */
costLC.setAttribute('width', 11); /* 12; account for stroke */
costLC.setAttribute('height', 10); /* 12 from middle; account for stroke */
costLC.setAttribute('style',
'fill: rgb(0, 0, 0); fill-opacity: 0; stroke-width: 2px; stroke: black;');
costLeg.insertBefore(costLC, costLeg.lastChild);
}")
pL %>% htmlwidgets::onRender(or)
JS 中的代码从document.querySelectorAll
更改为el.querySelectorAll
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.