簡體   English   中英

ggplot - 在 R 中的 x 軸上繪制類別的平均值

[英]ggplot - plot an average of categories on the x-axis in R

晚上好,

這是我的第一個問題,所以請善待。

我想使用 R Studio 分析包含 150 多個列和 300 行的數據集,但我是新手。 我的問題是我想用 ggplot 繪制折線圖或條形圖。 不幸的是,我無法在 x 軸上繪制類別 i 與該類別的平均值(帶性別)(無論是否使用 plot 或 ggplot)。 另一個問題是替換“。” 在圖表的標題(列名)中。

附上此問題的主要代碼以及使用 Excel 的圖表圖片(作為示例)。 在最好的情況下,我的代碼將為每個標題類別(列名的前兩個數字)創建一個帶有子類別(后兩個數字)的圖表。 但一開始我試圖用一個類別繪制一個圖表,但沒有奏效。

我會對反饋或提示感到高興,因為它不可能那么難,但我還沒有找到任何東西。

提前謝謝了。

PS:桑迪對這個問題的評論對我不起作用。

Roh_daten <- data.frame(Age=c(25,22,23,21,21,18),Geschlecht=c("m","w","m","m","m","m"),Test.Kette_01_01 = c(6,5,5,4,5,5),Test.String_01_02=c(2,5,5,3,3,4),Testchar_02_01 = c(0,5,5,4,6,6))
Laufzahl_i <- 1
Farbe_m="blue"#willkürlich festgelegt
Farbe_w="red"#willkürlich festgelegt

library(ggplot2)
library(stringr)

Links = function(text, num_char) {
  substr(text, 1, num_char)
}
Rechts = function(text, num_char) {
  substr(text, nchar(text) - (num_char-1), nchar(text))
}

for(i in 2:ncol(Roh_daten)) #nicht 1 da dies nur die ID ist
{
  #print(colnames(Roh_daten[i]))
  if(i==ncol(Roh_daten)) break()

  #colnames(Roh_daten[i]) <- c(String_in_string_replace(colnames(Roh_daten[i]),"\\.","\\ ","All"))

  if(all.equal(Roh_daten[,i], as.integer(Roh_daten[,i]))==TRUE)
  {
    assign(paste(colnames(Roh_daten[i]),"test_men",sep = "_"),mean(Roh_daten[,i][Roh_daten$Geschlecht == "m"],na.rm = TRUE))#erstellt aus dem paste String eine Variable
    assign(paste(colnames(Roh_daten[i]),"test_woman",sep = "_"),mean(Roh_daten[,i][Roh_daten$Geschlecht == "w"],na.rm = TRUE))
    assign(paste(colnames(Roh_daten[i]),"test_m_w",sep = "_"),mean(subset(Roh_daten[,i],Roh_daten$Geschlecht == "m" | Roh_daten$Geschlecht == "w"),na.rm = TRUE))

    if(Links(Rechts(colnames(Roh_daten[i]),5),2) == Links(Rechts(colnames(Roh_daten[i-1]),5),2)){#nur wenn stimmt alle -1
      #print(Links(Rechts(colnames(Roh_daten[i-1]),5),2))
      Laufzahl_i=Laufzahl_i+1
      if(Links(Rechts(colnames(Roh_daten[i]),5),2) == Links(Rechts(colnames(Roh_daten[i+1]),5),2)){#letztes element von alle mit der bed. von oben
      }else{
        #print(c("Es wurde ", Laufzahl_i, " Mal der gleiche Bereich erkannt."))
        Laufzahl_i <- 1

        Var_name_m <-  paste(colnames(Roh_daten[i]),"test_men",sep = "_")
        Var_name_w <-  paste(colnames(Roh_daten[i]),"test_woman",sep = "_")

        plot(get(Var_name_m),t="b",col=Farbe_m,ylim = c(0,6),yaxt="n",main = Links(Var_name_m,str_locate(Var_name_m,"_")-1),ylab="Wichtigkeit")
        text(x=get(Var_name_m),labels = as.character(round(get(Var_name_m),digits = 2)),pos=2,col = Farbe_m)
        text(x=get(Var_name_w),labels = as.character(round(get(Var_name_w),digits = 2)),pos=4,col = Farbe_w)
        axis(2, at = seq(0, 6, by = 0.5), las=2)
        legend(x ="topleft", legend = c("m","w"),col=c(Farbe_m, Farbe_w), bty = "o")
        points(get(Var_name_w),t="b",col=Farbe_w,ylim = c(0,6))

        p <- ggplot(data=Roh_daten[i],aes(x=get(Var_name_m),y=get(Var_name_m))) + #xlab(colnames(Roh_daten[,i]))
          #geom_line(linetype=2) +
          geom_point(size=1,col=Farbe_m) +
          geom_point(size=1,col=Farbe_w,aes(y=get(Var_name_w))) +
          theme(panel.border = element_rect(colour = "black", fill=NA, size=0.5))
          #geom_bar(stat="identity")
          #scale_y_continuous(breaks = seq(1,6,by=1)) 
        p
#ggplot(data=Roh_daten[i],aes(x=get(Var_name_m),y=get(Var_name_m))) + stat_summary(fun.y=mean, geom = "point")
      }
    }

  }else {
    print(paste(colnames(Roh_daten[i])," hat einen Fehler (String)"))
  }
}
p

Excel 圖表 - 示例

問題 1:繪制每個類別的每個性別的平均值

我不確定這是否正是您所要求的,但根據我的理解,您希望獲得與 excel 相同的圖。 Breifly,將每個類別的每個性別的平均值繪制為一條線或一個條形圖,並在其上顯示平均值。

根據您提供的示例,您可以使用dplyrtidyr庫根據性別對每列進行平均,並讓它們重塑以在ggplot繪圖。 在這里您可以按步驟進行操作:

首先,根據性別獲取每列的平均值:

library(dplyr)
Roh_daten %>% 
  group_by(Geschlecht) %>% 
  summarise_all(.funs = mean) 

# A tibble: 2 x 5
  Geschlecht   Age Test.Kette_01_01 Test.String_01_02 Testchar_02_01
  <fct>      <dbl>            <dbl>             <dbl>          <dbl>
1 m           21.6                5               3.4            4.2
2 w           22                  5               5              5  

接下來,我們要重塑這些數據以匹配要使用的ggplot2語法(簡要總結,x 值的唯一列,y 值的唯一列,以及每個類別的列),因此您可以使用該函數pivot_longertidyr

library(dplyr)
library(tidyr)
Roh_daten %>% 
  group_by(Geschlecht) %>% 
  summarise_all(.funs = mean) %>% 
  pivot_longer(., -c(Geschlecht, Age), names_to = "Variable", values_to = "Value")

# A tibble: 6 x 4
  Geschlecht   Age Variable          Value
  <fct>      <dbl> <chr>             <dbl>
1 m           21.6 Test.Kette_01_01    5  
2 m           21.6 Test.String_01_02   3.4
3 m           21.6 Testchar_02_01      4.2
4 w           22   Test.Kette_01_01    5  
5 w           22   Test.String_01_02   5  
6 w           22   Testchar_02_01      5  

最后,我們可以使用ggplot2得到這樣的條形圖:

library(dplyr)
library(tidyr)
library(ggplot2)
Roh_daten %>% 
  group_by(Geschlecht) %>% 
  summarise_all(.funs = mean) %>% 
  pivot_longer(., -c(Geschlecht, Age), names_to = "Variable", values_to = "Value") %>%
  ggplot(., aes(x = Variable, y = Value, group = Geschlecht))+
  geom_bar(stat = "identity", aes(fill = Geschlecht), position = position_dodge())+
  theme(legend.position = "top")+
  geom_label(aes(label = Value), position = position_dodge(0.9), vjust = -0.5)+
  ylim(0,5.5)

在此處輸入圖片說明

或者像這樣獲取線和點(庫ggrepel將有助於顯示標簽而不相互重疊:

library(dplyr)
library(tidyr)
library(ggplot2)
library(ggrepel)
Roh_daten %>% 
  group_by(Geschlecht) %>% 
  summarise_all(.funs = mean) %>% 
  pivot_longer(., -c(Geschlecht, Age), names_to = "Variable", values_to = "Value") %>%
  ggplot(., aes(x = Variable, y = Value, color = Geschlecht, group = Geschlecht))+
  geom_point()+
  geom_line()+
  theme(legend.position = "top")+
  geom_label_repel(aes(label = Value), vjust = -0.5)

在此處輸入圖片說明

這是你正在尋找的那種情節嗎? 如果沒有,您能否澄清您的問題,因為我不了解您的所有代碼。

問題 2:替換列名中的點

關於您關於替換“。”的第二個問題。 在數據集的列名中,您可以使用庫rebus

library(rebus)
gsub(DOT,"-", colnames(Roh_daten))

[1] "Age"               "Geschlecht"        "Test-Kette_01_01"  "Test-String_01_02" "Testchar_02_01"   

我希望它能回答你的問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM