Show negatives in Red in Plotly and R

随声附和 提交于 2021-02-08 11:23:21

问题


I want to show the negatives as red colour

Tried to look for solutions online but none found

plot_ly(x = ecomm_yoy2$YOY, y = ecomm_yoy2$Brand, type = 'bar', orientation = 'h') %>%
  layout(xaxis = list(title = "% YOY change in £ for June", dtick = 10)) %>% 
  layout(yaxis = list(categoryorder = "array", categoryarray = ecomm_yoy2$YOY)) %>%
  add_annotations(text = ecomm_yoy2$YOY, showarrow = F, xshift = 25)

Currently only shows blue


回答1:


Here is a possible solution using plotly's color and colors arguments:

ecomm_yoy2 <- data.frame(YOY = -19:20, Brand = 1:40)

plot_ly(ecomm_yoy2, x = ~YOY, y = ~Brand, type = 'bar', orientation = 'h', color = ~YOY < 0, colors = c("chartreuse3", "red"), name = ~ifelse(YOY < 0, "< 0", ">= 0")) %>%
  layout(xaxis = list(title = "% YOY change in £ for June", dtick = 10)) %>% 
  layout(yaxis = list(categoryorder = "array", categoryarray = ~YOY)) %>%
  add_annotations(text = ~YOY, showarrow = F, xshift = 25)

You might want to have a look at:

library(plotly)
library(listviewer)
schema(jsonedit = interactive())

which let's you navigate through plotly's available traces and their arguments.




回答2:


One easy way to do it is:

  1. Calculate a new variable with positive values as '1' & negative values as '0' and attach it to the dataset.

  2. While plotting, use color aesthetic to color the bars, according to the values of the column that was just created.



来源:https://stackoverflow.com/questions/57073397/show-negatives-in-red-in-plotly-and-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!