更改 R 中辅助 y 轴的绘图中的条形颜色

问题描述 投票:0回答:1

我一生都无法弄清楚如何更改该图中条形的颜色。我确信它并不像我想象的那么复杂,并且希望得到一些帮助。我添加了一些虚拟数据,因为我使用的实际数据是保密的。

covid_hospital_2 <- tibble(`Format Date` = as.Date(c('2022-01-01','2022-02-01','2022-03-01','2022-04-01','2022-05-01','2022-06-01','2022-07-01','2022-08-01','2022-09-01','2022-10-01')),
              `Total Inpatients` = c(180,67,100,89,123,50,134,99,101,170),
              `Proportion in ICU` = c(0.41,0.18,0.33,0.12,0.05,0.15,0.22,0.02,0.29,0.07))

covid_hosp_plot_v2 <- plot_ly(covid_hospital_2, x = ~`Format Date`, y = ~`Total Inpatients`, type = 'bar', name = 'Total Inpatients') |> 
  add_trace(x = ~`Format Date`, y = ~`Proportion in ICU`, type = 'scatter', mode = 'line', yaxis = 'y2', name = 'Proportion in ICU', line = list(color = '#17375E')) |> 
  layout(yaxis2 = list(overlaying = 'y', side = 'right', tickformat = '.0%', title = 'Proportion in ICU', range = c(0, 1)),
         margin = list(l = 50, r = 50, b = 50, t = 50),
         xaxis = list(tickformat = '%Y-%m-%d', dtick = 'M1', tickangle = -90, title = ''),
         yaxis = list(title = 'Total inpatients', range = c(0, max(covid_hospital_2$`Total Inpatients`))),
         legend = list(x = 0.3, y = -0.25, orientation = 'h'))

covid_hosp_plot_v2

我尝试过使用 Chat GPT,但它说要向 add_trace 函数添加标记属性,但这只是向该行添加标记。我还检查了 Stack Overflow 中的其他问题,但找不到任何匹配的内容。

我希望条形的颜色为“#84BDDC”

如果您需要更多信息,请告诉我。预先感谢!

r colors plotly
1个回答
1
投票

与线条设置类似,您必须设置

marker
的颜色。为了防止标记颜色被线条轨迹继承,我通过单独的
add_trace
:

添加了条形
library(plotly)

covid_hosp_plot_v2 <- plot_ly(covid_hospital_2, x = ~`Format Date`) |> 
  add_trace(
    y = ~`Total Inpatients`, 
    type = "bar",
    name = "Total Inpatients",
    marker = list(color = "#84BDDC")
  ) |>
  add_trace(
    x = ~`Format Date`, y = ~`Proportion in ICU`, type = "scatter",
    mode = "lines", yaxis = "y2", name = "Proportion in ICU",
    line = list(color = "#17375E")
  ) |>
  layout(
    yaxis2 = list(
      overlaying = "y", side = "right", tickformat = ".0%",
      title = "Proportion in ICU", range = c(0, 1)
    ),
    margin = list(l = 50, r = 50, b = 50, t = 50),
    xaxis = list(tickformat = "%Y-%m-%d", dtick = "M1", tickangle = -90, title = ""),
    yaxis = list(
      title = "Total inpatients",
      range = c(0, max(covid_hospital_2$`Total Inpatients`))
    ),
    legend = list(x = 0.3, y = -0.25, orientation = "h")
  )

covid_hosp_plot_v2

© www.soinside.com 2019 - 2024. All rights reserved.