R绘图仪为条形图设置自定义颜色
在我闪亮的应用程序中,我有一个R绘图仪为条形图设置自定义颜色,r,shiny,plotly,R,Shiny,Plotly,在我闪亮的应用程序中,我有一个plotly条形图,我想在生成的条形图中设置每列的特定颜色 #Here's some reproducible data df=data.frame(Month=c("Jan","Feb","Mar","Apr","May","Jun"),Criteria1=c(10,15,20,15,7,6),Criteria2=c(3,8,5,7,9,10),Criteria3=c(11,18,14,9,3,1)) #Plot colNames <- names(df
plotly
条形图,我想在生成的条形图中设置每列的特定颜色
#Here's some reproducible data
df=data.frame(Month=c("Jan","Feb","Mar","Apr","May","Jun"),Criteria1=c(10,15,20,15,7,6),Criteria2=c(3,8,5,7,9,10),Criteria3=c(11,18,14,9,3,1))
#Plot
colNames <- names(df)[-1] #Month is the first column
# Here is where I set the colors for each `Criteria`, assuming that the order of colors follows the same order as the factor levels of the `Criteria`.
p <- plotly::plot_ly(marker=list(colors=c('#CC1480', '#FF9673', '#E1C8B4')))
for(trace in colNames){
p <- p %>% plotly::add_trace(data = df, x = ~Month, y = as.formula(paste0("~`", trace, "`")), name = trace, type = "bar")
}
p %>%
layout(title = "Trend Over Time",showlegend = FALSE,
xaxis = list(title = ""),
yaxis = list (title = "Monthly Count of QoL Tweets"))
#这里有一些可复制的数据
df=数据帧(月=c(“一月”、“二月”、“三月”、“四月”、“五月”、“六月”),标准1=c(10,15,20,15,7,6),标准2=c(3,8,5,7,9,10),标准3=c(11,18,14,9,3,1))
#密谋
colNames您可以将颜色指定给向量:
colors <- c('#CC1480', '#FF9673', '#E1C8B4')
颜色我不认为这里有必要使用循环,当df
熔化时,下面提供了对特定级别颜色选择的更多控制,单个级别Criteria1
,Criteria2
,Criteria3
library(plotly)
library(reshape2)
#Yout data.frame
df <- data.frame(Month = c("Jan","Feb","Mar","Apr","May","Jun"),
Criteria1 = c(10,15,20,15,7,6),
Criteria2 = c(3,8,5,7,9,10),
Criteria3 = c(11,18,14,9,3,1))
melt(df, id.vars = 'Month') %>% plot_ly(x = ~Month, y = ~value, type = 'bar',
color = ~variable,
colors = c(Criteria1 = '#CC1480', Criteria2 = '#FF9673', Criteria3 = '#E1C8B4'))
library(plotly)
图书馆(E2)
#Yout data.frame
df%绘图(x=~月,y=~值,类型='条形',
颜色=~变量,
颜色=c(标准1='#CC1480',标准2='#FF9673',标准3='#E1C8B4'))
您可以添加您的输入数据或一些模拟数据吗?我已经编辑了我的问题,以包含一些可复制的数据。您不能将df
引用为df()
抱歉,我忘了删除()。但是它仍然没有按照我想要的顺序显示颜色
library("plotly")
df=data.frame(Month=c("Jan", "Feb","Mar", "Apr", "May", "Jun"),
Criteria1 = c(10, 15,20,15,7,6),
Criteria2 = c(3, 8, 5, 7, 9, 10),
Criteria3 = c(11, 18, 14, 9, 3, 1))
colNames <- names(df)[-1] #Month is the first column
colors <- c('#CC1480', '#FF9673', '#E1C8B4')
p <- plotly::plot_ly()
#colNames = c('Criteria1')
for(trace in colNames){
p <- plotly::add_trace(p,
x = df$Month,
y = df[,trace],
marker = list(color = colors[[match(trace, colNames)]]),
name = trace,
type = "bar")
}
p
library(plotly)
library(reshape2)
#Yout data.frame
df <- data.frame(Month = c("Jan","Feb","Mar","Apr","May","Jun"),
Criteria1 = c(10,15,20,15,7,6),
Criteria2 = c(3,8,5,7,9,10),
Criteria3 = c(11,18,14,9,3,1))
melt(df, id.vars = 'Month') %>% plot_ly(x = ~Month, y = ~value, type = 'bar',
color = ~variable,
colors = c(Criteria1 = '#CC1480', Criteria2 = '#FF9673', Criteria3 = '#E1C8B4'))