问题描述
我有一个看起来像这样的数据框:
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
向量上的颜色
解决方法
一种实现此目的的方法是利用可通过参数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
)
)