Изменение цветов коробок по группам ggplot2 - PullRequest
0 голосов
/ 09 июля 2020

У меня блестящие блочные диаграммы, и я хотел бы изменить цвета векторными «столбцами», изменить порядок легенды и переименовать ось x. Вы знаете, как это лучше всего сделать? Я пробовал использовать scale_fill_discrete и scale_x_discrete, и это не сработало. Спасибо!

dados7 <- reactive({ 
  dataset1() %>% filter(variable==input$frame) %>% 
    rename( var8 = regiao, var9 = imp, var10 = metodo)
})
cols<-c("green","orange", "red", "blue","pink","salmon","black")
renderPlotly({
title3<-paste(input$frame, "por região")
if (input$frame=="Taxa_Natalidade")
  
  r<- dados7() %>%
    ggplot(aes(x = var10, y = var9)) + 
    geom_boxplot(aes(fill = var10), position = position_dodge(0.9)) +
    facet_wrap(vars(var8)) 
  r
})

введите описание изображения здесь

Ответы [ 2 ]

0 голосов
/ 10 июля 2020

Ваш вопрос на самом деле состоит из нескольких частей в одной. Вы хотите:

  1. Изменить цвета для заливки на определенную c палитру.
  2. Изменить порядок легенды
  3. Переименовать ось x.

Самый простой - №3. Все, что вам нужно сделать, это переименовать ось x, указав в labs(x="new name for your axis"). Если вы меняете масштаб оси x с помощью функции scale_x_*, вы захотите переименовать внутри этой функции, поскольку labs() - это просто вспомогательная функция для различных функций scale_*_(name=...).

Теперь для На другие вопросы невозможно дать хороший ответ без хорошего набора данных, поэтому я собираюсь составить некоторые данные, используя набор данных iris.

set.seed(123)
df <- iris
df$rand_label <- sample(paste0('Type',1:3), nrow(df), replace=TRUE)

Теперь посмотрите полученную коробчатую диаграмму, чтобы использоваться для демонстрации:

p <- ggplot(df, aes(x=Species, y=Sepal.Length, fill=rand_label)) +
  geom_boxplot() + theme_classic()
p

enter image description here

Changing Colors

To change fill colors, you only need to specify via scale_fill_manual() by passing the list of colors to the values= argument. Caution: you must supply a list of colors that matches the number of levels in the factor used to define fill. In this example, df$rand_label contains 3 levels, so we need to supply a vector of 3 colors:

cols 

enter image description here

If you want to specify to which level the colors are assigned, instead of passing a character vector you can pass either a named vector or a list of "label name" = "color name". Note that order doesn't matter here, since everything is explicitly defined:

cols1 

enter image description here

Changing Ordering

You can change the order of the fill legend in two different ways: (1) change the order of the legend and the positioning on the plot, and (2) just change the order of the items in the legend itself. First, I'll show you the #1 case (changing order of legend and positioning on the plot).

Change order of legend and order on plot

Changing both is more typically what you will do, since we often like the order things appear in the legend to match the order in which they appear on the plot. The best way to do this is to refactor the column in question and pass an ordered vector to levels= matching the order you want. You then need to call ggplot() again with your re-leveled factor:

df$rand_label 

enter image description here

Note that the order of the colors is still applied the same, but the order of the items is different in the plot. The order in which the items appear in the legend is also different.

Change only order in the legend

If you want to adjust the order of items as they appear in the legend, you can use the breaks= argument within scale_fill_manual() to define the order in which the items appear. In this case, we can use this to return the levels to their original order in the plot above, but retain the mixed up ordering we defined by releveling the factor. Also note that since we're just passing cols and not the named vector cols1, the colors are applied according to how the levels appear in the legend (not the way in which they are ordered in the factor):

df$rand_label 

введите описание изображения здесь

Вы также можете использовать аналогичную стратегию для изменения порядка оси x: в этом случае вы должны рефакторинг df$Species и установить levels= в соответствии с вашим предпочтительным порядком.

0 голосов
/ 09 июля 2020

пробовали ли вы: scale_fill_manual (values ​​= c ("синий", "зеленый" и т. Д. c ...) Должно работать

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