2016-11-05 47 views
2

我想在帶有ggplot2(理想情況下,帶有標準圖的情況下)的條形圖上顯示有序因子的值。R - 如何使用ggplot2顯示軸上的有序因子的值

我有一個有序的因素這一個:

「怎麼是你滿意的練習:」 - 絕對不滿意=>值1 - 不滿意=>值2 - 滿意= >值3 - 非常滿意=>值4

我要繪製與所述平均值的barplot和值「絕對不滿意」 - >「非常滿意」的軸線,而不是1 - > 4.

是否有可能通過ggplot2做到這一點?在我看來,主要困難在於繪製因子的均值而不是值的分佈(實際上我的繪圖是將有序因子轉換爲整數)。

這是dput在我的數據集上的結果。

structure(c(3L, 2L, 3L, 2L, 2L, 3L, 2L, NA, 2L, 3L, 4L, 2L, 1L 
), .Label = c("pas du tout satisfait", "plutôt pas satisfait", 
"plutôt satisfait", "très satisfait"), class = c("ordered", 
"factor")) 

這裏是barplot的例子(而不在軸上的值...):

example

的代碼如下。

Toto <- structure(c(3L, 2L, 3L, 2L, 2L, 3L, 2L, NA, 2L, 3L, 4L, 2L, 1L 
), .Label = c("pas du tout satisfait", "plutôt pas satisfait", 
       "plutôt satisfait", "très satisfait"), class = c("ordered","factor")) 

TotoNumeric <- as.data.frame(as.integer(Toto)) 

DataForGggplot2 <- as.data.frame(round(sapply(X = TotoNumeric, FUN = "mean", na.rm = TRUE), 1)) 
colnames(DataForGggplot2) <- "Donnees" 
DataForGggplot2$Etiquette <- "the exercises" 

Graphe <- ggplot(data = DataForGggplot2, aes(x = Etiquette, y = Donnees)) + 
    geom_bar(stat = "identity", fill = "blue") + 
    scale_y_continuous(limits = c(0, 4)) 
    coord_flip() 

print(Graphe) 

如果我的要求不明確,我可以給你進一步的細節。

感謝

+0

我的示例中的x軸(帶有值的軸,而不是問題的標籤)。 – Kumpelka

+0

嘗試使用'scale_y_continuous(限制= c(0,4),labels = c(「」,levels(Toto)))''而不是 – Nate

+1

謝謝!簡單的終於... – Kumpelka

回答

1

有一個在scale_y_continuous稱爲labels一個選項,你可以用這個。

對於此示例,我假設您要使用的因子是Toto。由於您設置了0 - 4(即長度= 5)的限制,但Toto只有4個級別,所以我爲0的值添加了NA。您還可以將限制設置爲0 - 3或1 - 4,而無需添加NA的等級。

library(ggplot2) 

Toto <- structure(c(3L, 2L, 3L, 2L, 2L, 3L, 2L, NA, 2L, 3L, 4L, 2L, 1L 
), .Label = c("pas du tout satisfait", "plutôt pas satisfait", 
       "plutôt satisfait", "très satisfait"), class = c("ordered","factor")) 

TotoNumeric <- as.data.frame(as.integer(Toto)) 

DataForGggplot2 <- as.data.frame(round(sapply(X = TotoNumeric, FUN = "mean", na.rm = TRUE), 1)) 
colnames(DataForGggplot2) <- "Donnees" 
DataForGggplot2$Etiquette <- "the exercises" 

Graphe <- ggplot(data = DataForGggplot2, aes(x = Etiquette, y = Donnees)) + 
    geom_bar(stat = "identity", fill = "blue") + 
    scale_y_continuous(name="Toto", labels = c("NA", levels(Toto)),limits = c(0, 4)) 

coord_flip() 

print(Graphe) 

enter image description here

欲瞭解更多細節和例子,this是一個很好的資源。

+1

謝謝。我不需要「NA」值,所以我嘗試'限制= c(0,3)'誰工作,但限制= c(1,4)'不。 – Kumpelka

+0

另一種說法是:「限制=」似乎是強制性的。當我嘗試刪除時,我在f(...,self = self)中有一個錯誤_Error:中斷和標籤長度不同。是否有可能避免使用'limits ='來簡化代碼? – Kumpelka

+0

不客氣。 'limits = c(1,4)'也可以,但是你必須相應地設置'breaks'。 'limits'是必需的,但它可以設置爲'NA'來指代現有的最小值或最大值。儘管如此,我不會推薦它。我剛剛嘗試了一下,結果很糟糕。如果你想編程,那麼你可以設置數據的功能限制,例如'limits = c(1,max(df $ y)'。如果您的問題得到解答,請點擊綠色複選標記以引導未來的讀者找到答案。 –

相關問題