R Chorpleth Plotly Colorscale 在帧中移动时不断重置为默认值

R Chorpleth Plotly Colorscale Keeps Resetting to Default when Moving through Frames

提问人:Abhinav Reddy 提问时间:10/26/2022 更新时间:10/26/2022 访问量:52

问:

我目前正在绘制一张分区统计图,跟踪 1910 年至 2020 年美国各州的人口。数据被分类为分类变量,其中包含十年内每个州的百分比变化。当我运行代码时,第一年(1910 年)看起来是正确的,但是当按“播放”或将滑块移动到任何其他年份时,色阶将重置为默认值,并且离散刻度和刻度将替换为连续版本。老实说,我完全不明白为什么只有第一帧是正确的,当我导航到任何其他帧后返回第一帧时,它会变成像其他帧一样(色阶明智)。

这是我的代码: `

library(plotly)
library(dplyr)
library(readr)
library("RColorBrewer")

states <- read_csv("states.csv")

AllCountryPop <- read_csv("All50%d.csv", 
                         col_types = cols(Year = col_number(), 
                                          Percent = col_number()))%>%
  inner_join(states, by.x = State, by.x = state) %>%
  select(Year, Code, Percent, Category) %>%
  mutate(hover = paste(Code, "\n", 100*Percent, "%"))
  
AllCountryPop$Category = factor(AllCountryPop$Category)
AllCountryPop$Val = as.numeric(AllCountryPop$Category)
nfactor = length(levels(AllCountryPop$Category))
colr <- brewer.pal(n = nfactor,name = "Blues") #Color scale should be blue with five leves (for each category)
levels(AllCountryPop$Category) <- c("-30% - 0%" , "0% - 30%", "30% - 60%", "60% - 90%", "90% - 130%")
names(colr) = levels(AllCountryPop$Category)
colrS = function(n){
  CUTS = seq(0,1,length.out=n+1)
  rep(CUTS,ifelse(CUTS %in% 0:1,1,2))
}

graph_properties <- list(
  scope = 'usa',
  showland = TRUE,
  landcolor = toRGB("white"),
  color = toRGB("white")
)

font = list(
  family = "DM Sans",
  size = 15,
  color = "black"
)

label = list(
  bgcolor = "#EEEEEE",
  bordercolor = "transparent",
  font = font
)

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

  
p <- plot_geo(AllCountryPop, 
              locationmode = "USA-states", 
              frame = ~Year)%>%
      add_trace(locations = ~ Code, 
             locationmode = "USA-states", 
             z = AllCountryPop$Val,
             zmin = min(AllCountryPop$Val),
             zmax = max(AllCountryPop$Val),
             text = ~hover,
             hoverinfo = 'text',
             colorbar=list(tickvals=1:nfactor, ticktext=names(colr)),
            colorscale= colorScale) %>%
      layout(geo = graph_properties,
         title = "Population Percent Change in the US\n1910 - 2020",
         font = list(family = "DM Sans")) %>%
      config(displayModeBar = FALSE) %>%
      style(hoverlabel = label) %>%
            colorbar(title = "Percent")

p

`

如果我的CSV数据可能有用:

“states.csv”的前两行:"State","Abbrev","Code" "Alabama","Ala.","AL"

“All50%d.csv”的前两行:State,Percent,Year,Category Alabama,0.051,2020,0% - 30%

P.S. 第一次在这里提问时,如果我需要改变提问方式、提供信息等,请告诉我,

r plotly choroplethr

评论


答: 暂无答案