2016-06-10 109 views
6

下面,我有繪製分組條形圖的R代碼。ggplot在x軸上顯示錶達式

group_name = c('A_1x', 'A_1x', 'A_2x', 'A_2x', 'A_3x', 'A_3x', 'A_4x', 'A_4x') 

mydata2 <- data.frame(mygroup = group_name, 
         mysubgroup = factor(c("Yes", "No"), 
              levels = c("Yes", "No")), 
         value = c(60,40,90,10,55,45,88,12)) 


ggplot(mydata2, aes(mygroup, value, fill = mysubgroup)) + 
    geom_bar(position = "dodge", width = 0.5, stat = "identity")+ 
    coord_flip() 

目前,情節如下圖所示。但是,我想要在x軸上顯示錶達式,如下圖所示。

enter image description here

我已經試過這樣:

group_name = c(expression(A[1*x]),expression(A[1*x]), 
       expression(A[2*x]),expression(A[2*x]), 
       expression(A[3*x]),expression(A[3*x]), 
       expression(A[4*x]),expression(A[4*x])) 

但它提供了以下錯誤:

Error in as.data.frame.default(x[[i]], optional = TRUE) : 
    cannot coerce class ""expression"" to a data.frame 

如何解決呢?

回答

4

這是一個工作示例 - 我將group_name更改爲4個元素而不是8個,並將它們手動添加到ggplot表達式中。問題在於表達式類型不能是data.frame的列名稱。這逃避了這個問題。

library(ggplot2) 
group_name = c('A_1x', 'A_1x', 'A_2x', 'A_2x', 'A_3x', 'A_3x', 'A_4x', 'A_4x') 
mydata2 <- data.frame(mygroup = group_name, 
         mysubgroup = factor(c("Yes", "No"), 
              levels = c("Yes", "No")), 
         value = c(60,40,90,10,55,45,88,12)) 

group_name = c(expression(A[1*x]), 
       expression(A[2*x]), 
       expression(A[3*x]), 
       expression(A[4*x])) 

ggplot(mydata2, aes(mygroup, value, fill = mysubgroup)) + 
    geom_bar(position = "dodge", width = 0.5, stat = "identity")+ 
    coord_flip() + 
    scale_x_discrete(labels=group_name) # Adding the labels here 
+1

這在我看來,一個人應該能夠創造表達的載體,而不是鍵入每一個明確的聲明out。這是我可以用的最好的,但也許有一個更優雅的方法:'scale_x_discrete(labels = sapply(paste0(「A [」,1:4,「* x]」),function(i)parse(text = i))的)' – eipi10

2

labels可以是一個函數,

group_name = sprintf("A[%i*x]", rep(1:4,each=2)) 

# alternatively, use gsub with your original vector 
# group_name = c('A_1x', 'A_1x', 'A_2x', 'A_2x', 'A_3x', 'A_3x', 'A_4x', 'A_4x') 
# gsub("A_([0-9])x","A[\\1*x]", group_name) 

mydata2 <- data.frame(mygroup = group_name, 
         mysubgroup = factor(c("Yes", "No"), 
              levels = c("Yes", "No")), 
         value = c(60,40,90,10,55,45,88,12)) 


ggplot(mydata2, aes(mygroup, value, fill = mysubgroup)) + 
    geom_bar(position = "dodge", width = 0.5, stat = "identity")+ 
    coord_flip() + scale_x_discrete(labels = function(l) parse(text=l)) 

enter image description here