繁体   English   中英

如何在 R plotly 中反转颜色条的方向?

[英]How to reverse the direction of colorbar in R plotly?

我使用 plotly 的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放在颜色条的顶部,将最大值放在底部更合理,因为这些值是某个指标的等级。


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

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

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

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

Plot 1: reversescale = F或未指定

在此处输入图像描述

Plot 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

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM