在R中为直方图分配颜色

问题描述

我有一个看起来像这样的数据框:

Global.df.Selected <- structure(list(Year.of.Issuance = c(
  2014L,2017L,2016L,2017L
),Region.of.Risk = c(
  "North America","Europe","North America","North America"
),color = c(
  "#2874A6","#5DADE2","#2874A6","#2874A6"
)),row.names = c(
  NA,-6L
),class = "data.frame")

我想创建一个直方图并指定颜色(这些颜色已经基于风险区域)。 我已完成以下操作:

plotly::plot_ly(Global.df,x = ~Year.of.Issuance,color = ~Region.of.Risk) %>%
  plotly::add_histogram() %>%
  plotly::layout(yaxis = list(title="Y axis label"),legend = list(
           orientation = "h",# show entries horizontally
           xanchor = "center",# use center of legend as anchor
           x = 0.5,y = -0.15
         ))

如何密谋精确使用Global.df.Selected$color向量上的颜色

enter image description here

解决方法

一种实现此目的的方法是利用可通过参数colors传递给ploly的颜色的命名矢量。试试这个:

library(plotly)

# Make named color vector
colors <- Global.df.Selected %>%
  select(Region.of.Risk,color) %>%
  distinct() %>%
  tibble::deframe()

plotly::plot_ly(Global.df.Selected,x = ~Year.of.Issuance,color = ~Region.of.Risk,colors = colors) %>%
  plotly::add_histogram() %>%
  plotly::layout(
    yaxis = list(title = "Y axis label"),legend = list(
      orientation = "h",# show entries horizontally
      xanchor = "center",# use center of legend as anchor
      x = 0.5,y = -0.15
    )
  )

enter image description here

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...