[英]How to plot barchart with dual axis by plotly/plot_ly function in R?
I have data with 1 categorical and 3 numerical columns.我有 1 个分类列和 3 个数值列的数据。
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))
I need to plot barchart via plotly or plot_ly like this below, where sale and share columns are visualized in bars and 'cost' given by red line and reflected on second axis on right :我需要通过plotly或plot_ly绘制条形图,如下所示,其中销售和共享列以条形可视化,“成本”由红线给出,并反映在右侧的第二个轴上:
Here is an example, though it is really tricky to align the 2nd axis to the first in plotly.这是一个示例,尽管将第二个轴与第一个轴对齐确实很棘手。 May someone provide more elegant solution
可能有人提供更优雅的解决方案
library(plotly)
second_y_axis <- list(
overlaying = "y",
side = "right",
title = "<b>Cost</b>",
rangemode = "tozero"
)
plot_ly() %>%
add_trace(
x = ~ df$model,
y = ~ df$sale,
type = "bar",
name = "Sale",
marker = list(color = "#0001ff")
) %>%
add_trace(
x = ~ df$model,
y = ~ df$share,
type = "bar",
name = "Share",
marker = list(color = "#bebebe")
) %>%
add_trace(
x = ~ df$model,
y = ~ df$cost,
name = "Cost",
yaxis = "y2",
mode = "lines+markers",
type = "scatter"
) %>%
layout(
title = "",
xaxis = list(title = "Model"),
yaxis = list(title = "Sale & Share"),
yaxis2 = second_y_axis
) %>%
layout(
plot_bgcolor='#e5ecf6',
xaxis = list(
zerolinecolor = '#ffff',
zerolinewidth = 2,
gridcolor = 'ffff'),
yaxis = list(
zerolinecolor = '#ffff',
zerolinewidth = 2,
gridcolor = 'ffff'
)
)
Here is ggplot2 solution这是ggplot2解决方案
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))
library(ggplot2)
library(dplyr)
library(tidyr)
sale_share <- df %>%
select(model, share, sale) %>%
pivot_longer(share:sale, names_to = "var", values_to = "value")
cost <- df %>%
select(model, cost) %>%
# in this case there is no transform need so the value is 1
# second axis mostly needed when the scales are different
mutate(value_transform = cost * 1)
fill_color <- c("#0001ff", "#bebebe")
names(fill_color) <- c("sale", "share")
ggplot() +
geom_bar(data = sale_share,
aes(x = model, y = value, group = var, fill = var),
stat = "identity", position = position_dodge()) +
geom_line(data = cost,
aes(x = model, y = value_transform), group = 1,
color = "red") +
geom_point(data = cost,
aes(x = model, y = value_transform)) +
scale_y_continuous(name = "Sale & Share",
# transform second axis to y axis values in this case
# it is multiply by 1
sec.axis = sec_axis(trans = ~ . * 1, name = "Cost")) +
scale_fill_manual(values = fill_color)
Created on 2022-06-07 by the reprex package (v2.0.1)由reprex 包(v2.0.1) 创建于 2022-06-07
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.