我无权访问您的数据。所以我决定使用 plotly 包中的教程数据来演示如何使用 viridis 颜色。
连续变量
如果您阅读 的帮助页面plot_ly()
,您会看到它colors
被指定为 colorbrewer2.org 调色板名称(例如“YlOrRd”或“Blues”),或以十六进制“#RRGGBB”格式插入的颜色向量,或颜色像 colorRamp() 这样的插值函数。您可以做的是使用magma()
viridisLite 包创建颜色矢量。在这里我指定了colors = magma(50, alpha = 1, begin = 0, end = 1, direction = 1)
. n = 50 表示我想要颜色向量中有 50 种颜色。您想为自己的情况使用这个数字。
library(dplyr)
library(viridis)
library(plotly)
df <- read.csv("https://raw.githubusercontent.com/plotly/datasets/master/2011_us_ag_exports.csv")
df$hover <- with(df, paste(state, '<br>', "Beef", beef, "Dairy", dairy, "<br>",
"Fruits", total.fruits, "Veggies", total.veggies,
"<br>", "Wheat", wheat, "Corn", corn))
# give state boundaries a white border
l <- list(color = toRGB("white"), width = 2)
# specify some map projection/options
g <- list(scope = 'usa',
projection = list(type = 'albers usa'),
showlakes = TRUE,
lakecolor = toRGB('white'))
p <- plot_geo(df, locationmode = 'USA-states') %>%
add_trace(z = ~total.exports,
text = ~hover,
locations = ~code,
color = ~total.exports,
colors = magma(50, alpha = 1, begin = 0, end = 1, direction = 1)) %>%
colorbar(title = "Millions USD") %>%
layout(title = '2011 US Agriculture Exports by State<br>(Hover for breakdown)',
geo = g)
分类变量
After posting my answer, I thought you were using a categorical variable. I played around the example and think that it is tricky to create a chloropleth map with such a variable in plotly. At least, I can assign colors to polygons based on a categorical variable, but a color bar appears in a funny way. So I removed it. (If anybody can improve this part, please do so.)
Using the same data, I did the following. I created a categorical variable using ntile()
in the dplyr package. I randomly created 9 levels in total.exports
. Then, I created nine colors using magma()
. When I drew the map below, I used colors = foo[df$export_nth]
. This is basically creating 50 colors using foo
. export_nth
is used as index numbers. I hope this will help you to think how you can solve your situation.
mutate(df, export_nth = ntile(x = total.exports, n = 9)) -> df
# Create a magma color vector
foo <- magma(n = 9, alpha = 1, begin = 0, end = 1, direction = 1)
p <- plot_geo(df, locationmode = 'USA-states') %>%
add_trace(z = ~export_nth,
text = ~hover,
locations = ~code,
colors = foo[df$export_nth],
color = ~export_nth,
showscale = FALSE) %>%
layout(title = '2011 US Agriculture Exports by State<br>(Hover for breakdown)',
geo = g)