ggplot2 цвет штриховой полосы не может быть изменен должным образом

#r #ggplot2

Вопрос:

Я создал следующую перевернутую линейчатую диаграмму в ggplot2 (координатно перевернутая сгруппированная линейчатая диаграмма ярко — зеленого цвета), которая сработала просто отлично (Код 1).

Однако я попытался воссоздать ту же структуру сюжета с другими данными, в основном скопировав и адаптировав код с первого сюжета. Все в порядке, за исключением серого цвета вместо желаемого зеленого в руководстве по заполнению шкалы. Честно говоря, я не могу понять, почему это работает в первом сюжете, но не во втором. (Код 2)

КОД 1 (рабочий исходный сюжет)

 
#LIBRARIES
library (ggplot2)
library (dplyr)
library (data.table)
library (rdrop2)
library(tableHTML)
library (forcats)
  
  df<- data.frame(
    Komp = rep(c("Geschlecht", "Alter", "Niveau"), 6), 
    
    groupW = c(
      rep("1", 3),
      rep("2", 3),
      rep("3", 3),
      NA, NA, "4",
      NA, NA, "5",
      NA, NA, "6"
      
      
      
    ),
    
    
    valuesW = c (45, 14.9, 4.6, 54, 64.9, 5.3, 1, 19.8, 22.2, NA, NA, 15.4, NA, NA, 38.2, NA, NA, 14.2)
    
  ) 



df%>%
  ggplot( aes(x = fct_rev(Komp), y = valuesW, fill = fct_rev(groupW)))   
    geom_bar(position = "dodge", stat = "identity",color = "#404040", show.legend = FALSE, 
             #width = 1
    ) 
    #scale_fill_discrete(name = "Vergleichsgruppen", labels=c("Du", "Gesamtdurchschnitt", paste("Durchschnitt", (Daten[toupper(input$Code), "SP01_01"]-1),"-",(Daten[toupper(input$Code), "SP01_01"] 1), "Jahre" ),paste("Durchschnitt",Daten[toupper(input$Code), "Sportart_zurueckkodiert"]), Geschlecht)) 
    xlab("") 
    ylab("Prozent") 
    scale_fill_manual(values=rep( "#8DAE10", 6)) 
    coord_flip() 
    #geom_hline(yintercept = 10, lty = 8, col = "Red")
    geom_text(
      aes (label = ifelse(is.na(valuesW),"" ,paste(valuesW,"%"))),
      color = "black", hjust =-0.35 , size = 4, position = position_dodge(width= 0.9)) 
    
    #scale_x_discrete(limits= rev(levels(groupW))) 
    geom_text(aes(y=0, label = c(
      "Weiblich",  "10-13 Jahre","Keine Ebene",
      "Mxnnlich", "14-17 Jahre","Bezirksebene", 
      "Div.",  "18-23 Jahre","Landesebene",
      "", "",  "landesxbergreifende Ebene" , 
      "", "",  "nationale Ebene", 
      "","", "internationale Ebene")
    ),  color = "white", hjust = 0, size = 5, position = position_dodge(width= 0.9)) 
    scale_y_continuous(
      expand= c(0.04,0), label = scales::comma, position = "right"
    )
 

КОД 2 (серый участок, который должен быть таким же зеленым, как и первый)

 #LIBRARIES
library (ggplot2)
library (dplyr)
library (data.table)
library (rdrop2)
library(tableHTML)
library (forcats)


df<- data.frame(

  
  
  
    
  Komp = rep(c("Smartphone", "PC/Laptop", "Tablet", "TV", "Spielkonsole", "Smart-Watch", "E-Book-Reader", "Andere"), 2), 
  
  groupW = c(
    rep("ja", 8),
    rep("nein", 8)
    
    
    
  ),
  
  
  valuesW = c (100-0, 100-23.9, 100-41.3, 100-30.9, 100-51.5, 100-73.2, 100-89.8, 100-98.9 ,0, 23.9, 41.3, 30.9, 51.5, 73.2, 89.8, 98.9)
  
) 

df%>%
  ggplot( aes(x = fct_rev(Komp), y = valuesW, fill = fct_rev(groupW)))   
    geom_bar(position = "dodge", stat = "identity",color = "#8DAE10", show.legend = FALSE, 
             #width = 1
    ) 
    #scale_fill_discrete(name = "Vergleichsgruppen", labels=c("Du", "Gesamtdurchschnitt", paste("Durchschnitt", (Daten[toupper(input$Code), "SP01_01"]-1),"-",(Daten[toupper(input$Code), "SP01_01"] 1), "Jahre" ),paste("Durchschnitt",Daten[toupper(input$Code), "Sportart_zurueckkodiert"]), Geschlecht)) 
    xlab("") 
    ylab("Prozent") 
    scale_fill_manual(values=rep( "#8DAE10", 16), limits = c("Smartphone", "PC/Laptop", "Tablet", "TV", "Spielkonsole", "Smart-Watch", "E-Book-Reader", "Andere")) 
    coord_flip() 
    #geom_hline(yintercept = 10, lty = 8, col = "Red")
    geom_text(
      aes (label = round(valuesW,1)),
      color = "black", hjust =-0.35 , size = 4, position = position_dodge(width= 0.9)) 
    
    #scale_x_discrete(limits= rev(levels(groupW))) 
    geom_text(aes(y=0, label = groupW
    ),  color = "white", hjust = 0, size = 5, position = position_dodge(width= 0.9)) 
    scale_y_continuous(
      expand= c(0.04,0), label = scales::comma, position = "right"
    )
 

Есть идеи, где ошибка?

Ответ №1:

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

  1. используйте geom_col , а не geom_bar со статусом = «идентичность»
  2. поменяйте местами значения x и y и связанные с ними шкалы и т.д., Чтобы избежать использования coord_flip
  3. удалите limits аргумент в вызове, чтобы scale_fill_manual
  4. преобразуйте Komp в коэффициент, чтобы контролировать порядок значений в ggplot.
 library(ggplot2)
library(forcats)
library(dplyr)


komp_cat <- c("Smartphone", "PC/Laptop", "Tablet", "TV", "Spielkonsole", "Smart-Watch", "E-Book-Reader", "Andere")

df1<- data.frame(
  Komp = rep(komp_cat, 2), 
  
  groupW = c(
    rep("ja", 8),
    rep("nein", 8)),
  
  valuesW = c (100-0, 100-23.9, 100-41.3, 100-30.9, 100-51.5, 100-73.2, 100-89.8, 100-98.9 ,0, 23.9, 41.3, 30.9, 51.5, 73.2, 89.8, 98.9)
  
) 



df1 %>% 
  mutate(Komp = factor(Komp, levels = komp_cat)) %>% 
  ggplot( aes(x = valuesW, y = fct_rev(Komp), fill = rev(groupW)))   
  geom_col(position = "dodge", color = "#8DAE10", show.legend = FALSE) 
  xlab("Prozent") 
  ylab("") 
  scale_fill_manual(values = rep("#8DAE10", 2)) 
  geom_text(aes (label = round(valuesW,1)),
            color = "black", 
            hjust = -0.35, 
            size = 4, 
            position = position_dodge(width = 0.9)) 
  geom_text(aes(x=0, label = groupW),
            color = "white", 
            hjust = 0, 
            size = 5, 
            position = position_dodge(width = 0.9)) 
  scale_x_continuous(expand = c(0.04, 0), label = scales::comma, position = "bottom")
 

Создано 2021-09-22 пакетом reprex (v2.0.0)

Комментарии:

1. Как я уже сказал @Godrim, мне нужен точный порядок категорий, хотя, и если я удалю аргумент limits, я, возможно, решил одну проблему, но застрял с другой.

2. Значения Komp и groupW расположены в алфавитном порядке (как в кадре данных, так и в ggplot); В каком порядке вы хотите, чтобы они находились? Удаление ограничений в вашем примере КОДА 2 не влияет на порядок значений Komp и. groupW Возможно, было бы проще и менее запутанно задать новый вопрос с этим новым условием, а не корректировать вопрос. Обычно корректировку уровней факторов категориальной переменной лучше всего выполнять вне вызова ggplot

3. Оба ваших кода 2 и 3 имеют категорию «Andere» (== другое). Это то, что вызывает проблему?

4. Оставьте этот вопрос, поскольку он не только законен, но и может быть полезен для других.

5. Обновленный ответ, демонстрирующий, как управлять порядком значений в Komp

Ответ №2:

Если вы удалите limits = c("Smartphone", "PC/Laptop", "Tablet", "TV", "Spielkonsole", "Smart-Watch", "E-Book-Reader", "Andere")

Это должно придать всем полосам желаемый зеленый цвет.

 library (ggplot2)
library (dplyr)
library (data.table)
library (rdrop2)
library(tableHTML)
library (forcats)


df<- data.frame(

  
  
  
    
  Komp = rep(c("Smartphone", "PC/Laptop", "Tablet", "TV", "Spielkonsole", "Smart-Watch", "E-Book-Reader", "Andere"), 2), 
  
  groupW = c(
    rep("ja", 8),
    rep("nein", 8)
    
    
    
  ),
  
  
  valuesW = c (100-0, 100-23.9, 100-41.3, 100-30.9, 100-51.5, 100-73.2, 100-89.8, 100-98.9 ,0, 23.9, 41.3, 30.9, 51.5, 73.2, 89.8, 98.9)
  
) 

df%>%
  ggplot( aes(x = fct_rev(Komp), y = valuesW, fill = fct_rev(groupW)))   
    geom_bar(position = "dodge", stat = "identity",color = "#8DAE10", show.legend = FALSE, 
             #width = 1
    ) 
    #scale_fill_discrete(name = "Vergleichsgruppen", labels=c("Du", "Gesamtdurchschnitt", paste("Durchschnitt", (Daten[toupper(input$Code), "SP01_01"]-1),"-",(Daten[toupper(input$Code), "SP01_01"] 1), "Jahre" ),paste("Durchschnitt",Daten[toupper(input$Code), "Sportart_zurueckkodiert"]), Geschlecht)) 
    xlab("") 
    ylab("Prozent") 
    scale_fill_manual(values=rep( "#8DAE10", 16), ) 
    coord_flip() 
    #geom_hline(yintercept = 10, lty = 8, col = "Red")
    geom_text(
      aes (label = round(valuesW,1)),
      color = "black", hjust =-0.35 , size = 4, position = position_dodge(width= 0.9)) 
    
    #scale_x_discrete(limits= rev(levels(groupW))) 
    geom_text(aes(y=0, label = groupW
    ),  color = "white", hjust = 0, size = 5, position = position_dodge(width= 0.9)) 
    scale_y_continuous(
      expand= c(0.04,0), label = scales::comma, position = "right"
    )