【问题标题】:Rshiny Highchart: keeping fixed color for order-changing categories on x axisR Shiny Highchart:为 x 轴上的订单更改类别保持固定颜色
【发布时间】:2016-09-20 20:31:58
【问题描述】:

大家下午好,

我正在 Rshiny 中制作条形图。在 X 轴上,我显示了 3 个月。他们的顺序可能会根据用户的输入而改变。我想为每个月保持相同的颜色,无论它在 x 轴上的位置是什么:例如,我希望“Jan”系列为蓝色,无论它位于 X 轴上的第 3 位还是第 1 位。我在下面提供了一个简化的代码示例:

library("shiny")
library("highcharter")

data(citytemp)

ui <- fluidPage(
    h1("Highcharter EXAMPLE"),
    fluidRow(
        column(width = 8,
               highchartOutput("hcontainer",height = "500px")
        ),
        selectInput("option", label = "",  width = "100%",
                    choices = c("Tokyo", "NY"))
    )
)

server <- function(input, output) {
    data <- citytemp[,c("month","tokyo","new_york")]
    data = data[data$month%in%c("Dec","Jan","Feb","Mar"),]
    choose_Option <- reactive({
        sort_option <- input$option
        if(sort_option=="Tokyo"){
            data = data[order(data$tokyo),]
        }
        else{
            data = data[order(data$new_york),]
        }
        return(data)
    })
    output$hcontainer <- renderHighchart({
        data = choose_Option()
        data = data[1:3,] 
        colors_for_categories <- c()

        colors_fun <- function(month){
            if(month=="Dec"){return (c("#1B1858"))}
            if(month=="Jan"){return (c("#00A1DE"))}
            if(month=="Feb"){return (c("#2E28AB"))}
            if(month=="Mar"){return (c("#0D653C"))} 
        }

        colors_for_categories  <- colors_fun(data$month[[1]])
        for(m in 2:3){
            colors_for_categories  <- append(colors_for_categories ,colors_fun(data$month[[m]]))
        }
        chart <-  highchart() %>% 
            hc_chart(type = "bar") %>% 
            hc_title(text = "Monthly Average Temperature for main cities") %>% 
            hc_subtitle(text = "Source: WorldClimate.com") %>% 
            hc_xAxis(categories = data$month) %>% 
            hc_yAxis(title = list(text = "Temperature (C)")) 

        hc <- chart %>% hc_add_series(yAxis=0,name="Tokyo",data = data$tokyo,colorByPoint=TRUE,colors=colors_for_categories )
        hc <- hc %>% hc_add_series(yAxis=0,name="NY",data = data$new_york,colorByPoint=TRUE,colors=colors_for_categories )    

        return(hc)
    })
} 

shinyApp(ui = ui, server = server)

您可以在图表下方的选项中看到您可以选择东京或纽约。根据您的选择,二月和一月在 X 轴上的位置不同,但相关系列始终具有相同的颜色。 我实施的解决方案非常有限:它包括确定每个月的新位置(每次输入更改!),然后分配正确的颜色。但这需要对大量数据起作用,我认为这不是最好的方法。你对处理这个问题有什么想法/建议吗? 非常感谢您的帮助 ! 最好的,马齐亚

【问题讨论】:

    标签: r highcharts shiny


    【解决方案1】:

    问题解决了!该方法可能是创建一个包含所有颜色和月份的表格。 每个图表都使用同一个表,因此我们可以轻松地在上面创建 colors_for_categories。 如果您对此有任何疑问,请告诉我。

    最好的,马齐亚

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-06-25
      • 1970-01-01
      • 1970-01-01
      • 2019-06-28
      • 2021-09-16
      • 2018-03-29
      • 2021-01-13
      相关资源
      最近更新 更多