簡體   English   中英

如何通過 R 中的 plotly/plot_ly 函數繪制雙軸條形圖?

[英]How to plot barchart with dual axis by plotly/plot_ly function in R?

我有 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))

我需要通過plotlyplot_ly繪制條形圖,如下所示,其中銷售和共享列以條形可視化,“成本”由紅線給出,並反映在右側的第二個軸上 在此處輸入圖像描述

這是一個示例,盡管將第二個軸與第一個軸對齊確實很棘手。 可能有人提供更優雅的解決方案

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'
      )
    )

繪圖輸出

這是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)

reprex 包(v2.0.1) 創建於 2022-06-07

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM