0

我使用 R 接口plotly来绘制颜色条,它将连续变量映射到颜色渐变。通过 debault,plotly将最小值放在颜色栏的底部,将最大值放在颜色栏的顶部。图中显示了一个示例。

示例颜色条

现在我想反转整个颜色条,最小值在顶部。但是,我还没有找到(或者我错过了)实现我的目标的选项。有什么办法可以反转颜色条吗?


感谢@vestland 提供以下示例代码:

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')
)

fig <- plot_geo(df, locationmode = 'USA-states', reversescale = T)
fig <- fig %>% add_trace(
    z = ~total.exports, text = ~hover, locations = ~code,
    color = ~total.exports, colors = 'Purples'
  )
fig <- fig %>% colorbar(title = "Millions USD")
fig <- fig %>% layout(
    title = '2011 US Agriculture Exports by State<br>(Hover for breakdown)',
    geo = g
  )

fig

该参数reversescale反转值和颜色之间的映射。但是,我的目标是反转整个颜色条(不更改映射)。在我的情况下,将值1放在颜色条的顶部和底部的最大值更合理,因为这些值是某些指标的等级。


pure 的类似问题ggplot。我刚刚发现我无法反转颜色条ggplot

4

1 回答 1

0

看起来你正在使用plot_geo(). 在这种情况下,只需reversescale = T像这样包括:

plot_geo(df, locationmode = 'USA-states', reversescale = T)`

这对于使用颜色条的大多数其他功能也应该是有效的。

情节1:reversescale = F或未指定

在此处输入图像描述

情节2:reversescale = T

完整代码:

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')
)

fig <- plot_geo(df, locationmode = 'USA-states', reversescale = T)
fig <- fig %>% add_trace(
    z = ~total.exports, text = ~hover, locations = ~code,
    color = ~total.exports, colors = 'Purples'
  )
fig <- fig %>% colorbar(title = "Millions USD")
fig <- fig %>% layout(
    title = '2011 US Agriculture Exports by State<br>(Hover for breakdown)',
    geo = g
  )

fig

在此处输入图像描述

于 2021-02-06T11:58:05.057 回答