You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R语言中修改带双Y轴的Plotly柱状图颜色的方法

修改Plotly柱状图颜色的解决方案

你只需在创建柱状图的初始plot_ly()调用中,通过marker = list(color = '#84BDDC')参数指定柱状图颜色即可。以下是修改后的完整代码及说明:

修改后的代码

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',
                              marker = list(color = '#84BDDC')) |> 
  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

关键说明

  • Plotly中柱状图(type = 'bar')的颜色由marker参数定义,而折线图的颜色才用line参数,这是两者的区别。
  • 你之前尝试的markers属性是针对散点图的标记点设置,因此不会对柱状图颜色产生影响。

内容的提问来源于stack exchange,提问作者Renee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 19:06:28