在R Plotly条形图中为痕迹添加空白条

时间:2017-06-02 16:21:59

标签: r dplyr plotly

我有以下数据框(dput(df)):

structure(list(lpc = c("Amory", "Appalachian", "Athens", "Blue Ridge", 
"Bolivar", "Bowling Green", "Bristol TN", "Bristol VA", "Brownsville", 
"Gallatin"), district = c("NMPPA", "ADPDA", "SDPDA", "SDPDA", 
"WDMA", "KPPA", "ADPDA", "ADPDA", "WDMA", "CDMA"), average = c(21679, 
185334, 66354, 131739, 45450, 137298, 162464, 79929, 21795, 94370
)), class = "data.frame", row.names = c(NA, 10L), .Names = c("lpc", 
"district", "average"))

我有一个与Plotly一起使用的功能,如下所示:

plot_district <- function (plot, dname) 
{
    if (dname == "ADPDA") {
        plot %>% filter(district == dname) %>% add_bars(x = ~lpc, 
            y = ~average, name = dname, type = "bar")
    }
    else {
        plot %>% filter(district == dname) %>% add_bars(x = ~lpc, 
            y = ~average, name = dname, type = "bar")
    }
}

使用此函数(plot_district)和此数据框(df),我在dplyr的帮助下制作了以下图:

df %>%
  arrange(district, average, lpc) %>%
  plot_ly() %>%
  add_fun(plot_district, 'ADPDA') %>%
  add_fun(plot_district, 'CDMA') %>%
  add_fun(plot_district, 'KPPA') %>%
  add_fun(plot_district, 'NMPPA') %>%
  add_fun(plot_district, 'SDPDA') %>%
  add_fun(plot_district, 'WDMA') %>%
  layout(xaxis = list(categoryorder = 'array', categoryarray = 'average'))

视觉: result

但是,我想在每个跟踪中添加1个空白数据条,除了第一个跟踪外,这样会在图表上的每个跟踪之间产生视觉差距。我尝试通过添加一个rbind('')来改变我的功能:

plot_district <- function (plot, dname) 
    {
        if (dname == "ADPDA") {
            #this will always be the first trace and it doesn't need space
            plot %>% filter(district == dname) %>% add_bars(x = ~lpc, 
                y = ~average, name = dname, type = "bar")
        }
        else {
            #this will be every other trace and they will need space after them
            #added the rbind() below
            plot %>% filter(district == dname) %>% rbind('') %>% add_bars(x = ~lpc, 
                y = ~average, name = dname, type = "bar")
        }
    }

这允许我运行以下代码而不会出错:

df %>% filter(district == 'CDMA') %>% rbind('') %>% plot_ly(x = ~lpc, y = ~average, name = 'CDMA', type = 'bar')

但是只要我运行整个图表的代码,就会出现以下错误:

Error in UseMethod("filter_") : 
  no applicable method for 'filter_' applied to an object of class "list"

如何为每条迹线添加空白条?

0 个答案:

没有答案