如何基于分类变量在R Plotly中创建叶绿素图?

时间:2019-12-29 00:35:54

标签: r maps plotly categorical-data

我正在尝试创建一个美国的绿藻色图,该色度图使用分类变量作为州色,但是我只能得到一个空白图。地物图与分类数据兼容吗?如果是这样,语法会如何变化?

对于我的数据,我只是简单地上载一个由状态组成的行表,并随机地包含“良好”,“不良”,“确定”之一。

如何更改下面的代码才能使其正常工作?我尝试了一种变通方法,该方法可以稍微改变状态的颜色,但是颜色栏会变色。 (value4是我的“良好”,“不良”,“确定”的类别变量)

很抱歉,如果我的问题不清楚或我的信息不好。如果有人有其他问题,我可以回答。预先感谢

foo <- brewer.pal(n = 3,
                        name = "Set1")

df <- mutate(df, test = ntile(x = value4, n = 3))

cw_map <- plot_ly(
  data = df,
  type = "choropleth",
  locations = ~ state,
  locationmode = "USA-states",
  color = ~ test,
  colors = foo[df$test],
  z = ~ test
) %>%
  layout(geo = list(scope = "usa"))

print(cw_map)

1 个答案:

答案 0 :(得分:2)

您需要在代码形式中包含状态,所以我们从此开始:

STATES <-c("AL", "AK", "AZ", "AR", "CA", "CO", "CT", "DE", "FL", "GA", 
"HI", "ID", "IL", "IN", "IA", "KS", "KY", "LA", "ME", "MD", "MA", 
"MI", "MN", "MS", "MO", "MT", "NE", "NV", "NH", "NJ", "NM", "NY", 
"NC", "ND", "OH", "OK", "OR", "PA", "RI", "SC", "SD", "TN", "TX", 
"UT", "VT", "VA", "WA", "WV", "WI", "WY")

就像您所做的那样,我们为每个州提供随机值4:

df = data.frame(state=STATES,
value4=sample(c("Good", "Bad", "OK."),length(STATES),replace=TRUE))

然后我们将您的value4作为因子,将颜色等作为您之前做过的事情:

df$value4 = factor(df$value4)
df$test = as.numeric(df$value4)
nfactor = length(levels(df$value4))
foo <- brewer.pal(n = nfactor,name = "Set1")
names(foo) = levels(df$value4)

要以离散形式显示颜色图例,您需要将其作为数据框提供,该数据框以 z的相对比例定义间断。它在R中没有很好地记录,我用@emphet's plotly forum post@marcosandri's SO post的信息编写了以下n个因子的解决方案:

Z_Breaks = function(n){
CUTS = seq(0,1,length.out=n+1)
rep(CUTS,ifelse(CUTS %in% 0:1,1,2))
}

colorScale <- data.frame(z=Z_Breaks(nfactor),
col=rep(foo,each=2),stringsAsFactors=FALSE)

          z     col
1 0.0000000 #E41A1C
2 0.3333333 #E41A1C
3 0.3333333 #377EB8
4 0.6666667 #377EB8
5 0.6666667 #4DAF4A
6 1.0000000 #4DAF4A

然后我们绘图:

cw_map <- plot_ly(
  data = df,
  type = "choropleth",
  locations = ~ state,
  locationmode = "USA-states",
  z = df$test,
  colorscale=colorScale,
  colorbar=list(tickvals=1:nfactor, ticktext=names(foo))
) %>%
layout(geo = list(scope = "usa")) 

enter image description here