Merging legends in plotly subplot

dan

I have several groups where for each I have several classes for which I measured continuous values:

set.seed(1)

df <- data.frame(value = c(rnorm(100,1,1), rnorm(100,2,1), rnorm(100,3,1),
                           rnorm(100,3,1), rnorm(100,1,1), rnorm(100,2,1),
                           rnorm(100,2,1), rnorm(100,3,1), rnorm(100,1,1)),
                 class = c(rep("c1",100), rep("c2",100), rep("c3",100),
                           rep("c2",100), rep("c4",100), rep("c1",100),
                           rep("c4",100), rep("c3",100), rep("c2",100)),
                 group = c(rep("g1",300), rep("g2",300), rep("g3",300)))

df$class <- factor(df$class, levels =c("c1","c2","c3","c4"))
df$group <- factor(df$group, levels =c("g1","g2","g3"))

Not each group in the data has the same classes, or put differently each group has a subset of all classes.

I'm trying to generate R plotly density curves for each group, color-coded by class, and then combine them all to a single plot using plotly's subplot function.

This is what I'm doing:

library(dplyr)
library(ggplot2)
library(plotly)


set.seed(1)

df <- data.frame(value = c(rnorm(100,1,1), rnorm(100,2,1), rnorm(100,3,1),
                           rnorm(100,3,1), rnorm(100,1,1), rnorm(100,2,1),
                           rnorm(100,2,1), rnorm(100,3,1), rnorm(100,1,1)),
                 class = c(rep("c1",100), rep("c2",100), rep("c3",100),
                           rep("c2",100), rep("c4",100), rep("c1",100),
                           rep("c4",100), rep("c3",100), rep("c2",100)),
                 group = c(rep("g1",300), rep("g2",300), rep("g3",300)))

df$class <- factor(df$class, levels =c("c1","c2","c3","c4"))
df$group <- factor(df$group, levels =c("g1","g2","g3"))

plot.list <- lapply(c("g1","g2","g3"), function(g){
  density.df <- do.call(rbind,lapply(unique(dplyr::filter(df, group == g)$class),function(l)
    ggplot_build(ggplot(dplyr::filter(df, group == g & class == l),aes(x=value))+geom_density(adjust=1,colour="#A9A9A9"))$data[[1]] %>%
      dplyr::select(x,y) %>% dplyr::mutate(class = l)))
  plot_ly(x = density.df$x, y = density.df$y, type = 'scatter', mode = 'lines',color = density.df$class) %>%
    layout(title=g,xaxis = list(zeroline = F), yaxis = list(zeroline = F))
})
subplot(plot.list,nrows=length(plot.list),shareX=T)

Which gives: enter image description here

The problems I'd like to fix are:

  1. Have the legend appear only once (right now it repeats for each group) merging all classes
  2. Have the title appear in each of the subplots rather than only for the last plot at is it is now. (I know that I could simply have the group name as the x-axis titles but I'd rather save that space because in reality I have more than 3 groups)
Bappa Das

You can use the following code

library(tidyverse)
library(plotly)

ggplotly(
  ggplot(df, aes(x=value, col = class)) + 
  geom_density(adjust=1) + 
  facet_wrap(~group, ncol = 1) +
    theme_minimal() + 
    theme(legend.position = 'top')
)

which gives me the following plot enter image description here

Эта статья взята из Интернета, укажите источник при перепечатке.

Если есть какие-либо нарушения, пожалуйста, свяжитесь с[email protected] Удалить.

Отредактировано в
0

я говорю два предложения

0обзор
Войти в системуУчаствуйте в комментариях

Статьи по теме

Matplotlib Legends не работает

Matplotlib Legends не работает

В R plotly subplot graph, как показать только одну легенду?

Отображение всех заголовков сюжета в plotly :: subplot

plotly cumulative animation does not work for subplot in R

Plotly: как получить значения для основных тиков и линий сетки?

как указать цвет для каждого графика в сценарии подзаголовка с помощью plotly

порядок строк с plotly

Plotly: How to add axis layouts into a subplot?

Автоматическая настройка диапазона оси, чтобы маркер поместился в Plotly

Plotly: How to handle overlapping colorbar and legends?

Plotly Legend Item Names in Subplot Graph with Loop

построить линейную диаграмму с помощью plotly, когда всегда есть разное количество переменных / столбцов

определить цветовую схему при построении линейного графика с помощью plotly

Отображение нескольких изображений в сетке с помощью subplot ()

Plotly: как обрабатывать текст различного размера на графике с накоплением воронок?

Ошибка при попытке войти на страницу разработчика League of Legends

Добавление плоскости регрессии к трехмерной точечной диаграмме в Plotly

Evitar legendas duplicadas com R plotly subplot resulta em pontos ausentes

How can I cut the large space at the bottom of the subplot in plotly?

Невозможно объединить графики с помощью команды subplot

R-plotly: Subplot показывает только нижний график

Single legend for Plotly subplot for line plots created from two data frames in R

Plotly: How to display legends for a sunburst diagram?

как строить разные типы диаграмм с помощью plotly и make_subplot в python

Регулировка высоты и ширины Plotly :: subplot в R Shiny

How to add vertical line to legends, created via add_vline method in plotly python

Заголовки аннотаций plotly :: subplot исчезают в R Shiny

Plotly: How to plot candlestick charts on a subplot?

TOP список

  1. 1

    Распределение Рэлея Curve_fit на Python

  2. 2

    How to click an array of links in puppeteer?

  3. 3

    (fields.E300) Поле определяет связь с моделью, которая либо не установлена, либо является абстрактной.

  4. 4

    Modbus Python Schneider PM5300

  5. 5

    Elasticsearch - Нечеткий поиск не дает предложения

  6. 6

    Как добавить Swagger в веб-API с поддержкой OData, работающий на ASP.NET Core 3.1

  7. 7

    TypeError: store.getState não é uma função. (Em 'store.getState ()', 'store.getState' é indefinido, como posso resolver esse problema?

  8. 8

    Перебирайте несколько столбцов в фрейме данных Panda и находите уникальные значения подсчета

  9. 9

    Проблемы со сборкой Python Image Registration Toolkit

  10. 10

    В типе Observable <unknown> отсутствуют следующие свойства из типа Promise <any>.

  11. 11

    Vue js CLI 2 импортирует и использует плагин javascript

  12. 12

    Автозаполнение с Java, Redis, Elastic Search, Монго

  13. 13

    Текущая ветка не настроена для извлечения В конфигурации не найдено значение для ключа branch.master.merge

  14. 14

    SQL Вычтите две строки друг от друга в одном столбце, чтобы получить результат

  15. 15

    How to normalize different curves drawn with geom = "step" when using stat_summary

  16. 16

    Merging legends in plotly subplot

  17. 17

    ViewPager2 мигает / перезагружается при смахивании

  18. 18

    Vue 2 / Vue CLI 3: создание асинхронных однофайловых компонентов

  19. 19

    как я могу удалить vue cli 2?

  20. 20

    Ошибка «LINK: фатальная ошибка LNK1123: сбой при преобразовании в COFF: файл недействителен или поврежден» после установки Visual Studio 2012 Release Preview

  21. 21

    Single legend for Plotly subplot for line plots created from two data frames in R

популярныйтег

файл