R Plotly中的自定义颜色 [英] custom colors in R Plotly

查看:781
本文介绍了R Plotly中的自定义颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前是Plotly的初学者,遇到了我似乎无法解决的问题.我有条理排列的条形图,但我不知道如何为每个类别着色.我当前正在使用R.

I'm currently a beginner in Plotly and have a problem I can't seem to solve. I have my plotly stacked bar chart but I don't know how to color each individual category. I am currently using R.

这是我当前的堆积条形图:

This is my current stacked bar chart:

我当前的代码是:

p = plot_ly(x, x = day, y = count, type = "bar", group = status) %>% layout(barmode = "stack", showlegend = T)

我尝试使用"color = "参数和标记,但是没有正确为我的图形着色.

I've tried using the "color = " parameter and also markers, but nothing correctly colors my graph.

推荐答案

您需要为color参数指定一个因子,然后为colors参数指定颜色的向量.

You need to specify a factor for the color parameters, and then a vector of colours for the colors parameter.

这是一个简单的解决方案.在绘制之前,请注意数据框上所需的排序.

Here is a simple solution. Note the ordering required on the data frame before plotting.

require(dplyr)
require(plotly)

set.seed(42)

df <- data.frame(x = rep(LETTERS[1:5], 3), 
                 y = rexp(15, rate = 0.5),
                 z = c(rep("Adam", 5), rep("Arthur", 5), rep("Ford", 5)))
df <- arrange(df, desc(z))

plot_ly(df, 
        x = x, 
        y = y, 
        color = z, 
        colors = c("grey50", "blue", "red"), 
        type = "bar") %>% 
    layout(barmode = "stack")

数据框上的排序很奇怪.我本以为plot_ly将使用级别的顺序,但不会.

The ordering on the data frame matters strangely. I would have thought plot_ly would use the order of the levels but it doesn't.

本示例使用plotly3.x.x.如果您使用plotly 4.x.x或更高版本,则此代码可能无法按原样工作.详情请参阅此处: https://www. r-bloggers.com/upgradeing-to-plotly-4-0-and-above/

This example uses plotly 3.x.x. If you use plotly 4.x.x or above, this code may not work as is. See here for more details: https://www.r-bloggers.com/upgrading-to-plotly-4-0-and-above/

这篇关于R Plotly中的自定义颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆