Подгруппа сгруппированная легенда для сгруппированных гистограмм - PullRequest
0 голосов
/ 05 мая 2019

Я пытаюсь добавить сгруппированную легенду для сюжета в серию гистограмм GROUPED в plotly . Я нашел множество примеров сгруппированных легенд подгруппы для диаграмм в целом (например, последний графический пример здесь: https://plot.ly/r/legend/),, но я не могу заставить метод legendgroup = ~ работать для гистограмм GROUPED.

У меня есть данные опросов за два разных года (2017 и 2019 годы) по ряду действующих подразделений в моей компании. Я хочу показать результаты опроса 2017 и 2019 гг. Рядом для каждого операционного блока в отдельности в формате сгруппированных столбцов с диаграммой для каждого операционного блока. Единственный элемент, который не работает, - это легенда для года опроса (2017 или 2019), который я хочу проработать на всех графиках.

library(data.table)
library(plotly)

# Dummy data 
data <- data.table(Group = rep(c("Business_Unit_1","Business_Unit_2"), each = 4),
                   Question = rep(c("Happy","Ethics","Happy", "Ethics"), each = 2),
                   Year = c("2017", "2019", "2017", "2019", "2017", "2019", "2017", "2019"),
                   Prop = c(.9, .95, .8, .75, .7, .8, .8, .97))

# Grouped bar chart 1                    
plot_1 <- plot_ly() %>%
  add_trace(x = ~ data[Group == "Business_Unit_1" & Year == "2017", (Question)],
            y = ~ data[Group == "Business_Unit_1" & Year == "2017", (Prop)],
            name = "2017",
            type = 'bar',
            marker = list(color = 'rgb(158,202,225)',
                          line = list(color = 'rgb(8,48,107)', width = 1.5))) %>%
  add_trace(x = ~ data[Group == "Business_Unit_1" & Year == "2019", (Question)],
            y = ~ data[Group == "Business_Unit_1" & Year == "2019", (Prop)],
            name = "2019",
            type = 'bar',
            marker = list(color = 'rgb(58,200,225)',
                          line = list(color = 'rgb(8,48,107)', width = 1.5))) %>%
  layout(yaxis = list(title = 'Proportion'),
         annotations = list(x = 0.5 , y = 1.05, text = "Business_Unit_1", showarrow = F, xref = 'paper', yref = 'paper'),
         barmode = 'group')

# Grouped bar chart 2
# Right now I am just hiding the second legend
plot_2 <- plot_ly() %>%
  add_trace(x = ~ data[Group == "Business_Unit_2" & Year == "2017", (Question)],
            y = ~ data[Group == "Business_Unit_2" & Year == "2017", (Prop)],
            name = "2017",
            type = 'bar',
            showlegend = FALSE,
            marker = list(color = 'rgb(158,202,225)',
                          line = list(color = 'rgb(8,48,107)', width = 1.5))) %>%
  add_trace(x = ~ data[Group == "Business_Unit_2" & Year == "2019", (Question)],
            y = ~ data[Group == "Business_Unit_2" & Year == "2019", (Prop)],
            name = "2019",
            type = 'bar',
            showlegend = FALSE,
            marker = list(color = 'rgb(58,200,225)',
                          line = list(color = 'rgb(8,48,107)', width = 1.5))) %>%
  layout(yaxis = list(title = 'Proportion'),
         annotations = list(x = 0.5 , y = 1.05, text = "Business_Unit_2", showarrow = F, xref = 'paper', yref = 'paper'),
         barmode = 'group')

# Create the subplot
plots <- subplot(plot_1, plot_2, shareY = TRUE, nrows = 1)
plots

При написании этого кода легенда связана только с первым сюжетом, а легенда второго сюжета скрыта. Может ли кто-нибудь помочь, пожалуйста?

1 Ответ

0 голосов
/ 23 июля 2019

Вы можете установить legendgroup вручную, как имена следов, которые вы сделали. Просто вставьте legendgroup = "2017" или legendgroup = "2019" в add_trace, и все будет работать нормально.

Вот ваш код с этим небольшим изменением:

library(data.table)
library(plotly)
# Dummy data 
data <- data.table(Group = rep(c("Business_Unit_1","Business_Unit_2"), each = 4),
                   Question = rep(c("Happy","Ethics","Happy", "Ethics"), each = 2),
                   Year = c("2017", "2019", "2017", "2019", "2017", "2019", "2017", "2019"),
                   Prop = c(.9, .95, .8, .75, .7, .8, .8, .97))

# Grouped bar chart 1                    
plot_1 <- plot_ly() %>%
  add_trace(x = ~ data[Group == "Business_Unit_1" & Year == "2017", (Question)],
            y = ~ data[Group == "Business_Unit_1" & Year == "2017", (Prop)],
            name = "2017",
            type = 'bar',
            legendgroup = "2017", ### Legend 2017
            marker = list(color = 'rgb(158,202,225)',
                          line = list(color = 'rgb(8,48,107)', width = 1.5))) %>%
  add_trace(x = ~ data[Group == "Business_Unit_1" & Year == "2019", (Question)],
            y = ~ data[Group == "Business_Unit_1" & Year == "2019", (Prop)],
            name = "2019",
            type = 'bar',
            legendgroup = "2019", ### Legend 2019
            marker = list(color = 'rgb(58,200,225)',
                          line = list(color = 'rgb(8,48,107)', width = 1.5))) %>%
  layout(yaxis = list(title = 'Proportion'),
         annotations = list(x = 0.5 , y = 1.05, text = "Business_Unit_1", showarrow = F, xref = 'paper', yref = 'paper'),
         barmode = 'group')

# Grouped bar chart 2
# Right now I am just hiding the second legend
plot_2 <- plot_ly() %>%
  add_trace(x = ~ data[Group == "Business_Unit_2" & Year == "2017", (Question)],
            y = ~ data[Group == "Business_Unit_2" & Year == "2017", (Prop)],
            name = "2017",
            type = 'bar',
            legendgroup = "2017", ### Legend 2017
            showlegend = FALSE,
            marker = list(color = 'rgb(158,202,225)',
                          line = list(color = 'rgb(8,48,107)', width = 1.5))) %>%
  add_trace(x = ~ data[Group == "Business_Unit_2" & Year == "2019", (Question)],
            y = ~ data[Group == "Business_Unit_2" & Year == "2019", (Prop)],
            name = "2019",
            type = 'bar',
            legendgroup = "2019", ### Legend 2019
            showlegend = FALSE,
            marker = list(color = 'rgb(58,200,225)',
                          line = list(color = 'rgb(8,48,107)', width = 1.5))) %>%
  layout(yaxis = list(title = 'Proportion'),
         annotations = list(x = 0.5 , y = 1.05, text = "Business_Unit_2", showarrow = F, xref = 'paper', yref = 'paper'),
         barmode = 'group')

# Create the subplot
plots <- subplot(plot_1, plot_2, shareY = TRUE, nrows = 1)
plots

Вот вывод:

Все

all

Только 2017:

2017

Только 2019:

2019

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...