2016-10-30 23 views
2

mpg數據集爲例,我想使用facet_grid(),其中只有相關模型在每個製造商下列出。具有facet_grid,free_x不起作用的水平條形圖

此代碼似乎工作(左圖)

library(ggplot2) 
qplot(cty, model, data=mpg) + 
    facet_grid(manufacturer ~ ., scales = "free", space = "free") 

但是這一次不(右)

ggplot(mpg) + 
    geom_bar(aes(x = model, y = cty), stat = "identity") + 
    coord_flip() + 
    facet_grid(manufacturer ~ ., scales = "free", space = "free") 

enter image description here

我看到這個線程,但不能得到它的工作: Horizontal bar chart with facets

Th oughts?

+0

也許相關http://stackoverflow.com/questions/12560858/using-coord-flip-with-facet-wrapscales-free-y-in-ggplot2-seems-to-give-u, http://stackoverflow.com/questions/25052000/in-ggplot2-coord-flip-and-free-scales-dont-work-together,http://stackoverflow.com/questions/39811038/removing-y-categorical-變量-facet-grid – user20650

+0

謝謝。看到這一個太:http://stackoverflow.com/questions/35940521/combining-horizo​​nal-bars-with-facet-grid-in-ggplot – yake84

回答

4

TL; DR:space="free"scales="free"不適用於coord_flip。相反,使用ggstance包中的geom_barh(水平條几何),這可以避免需要coord_flip。下面的細節。

space="free"scales="free"不適用於coord_flip。這對繪圖點無關緊要,因爲使用點可以切換x和y軸,並且geom_point仍然可以工作,從而避免需要coord_flip。但是,geom_bar預計值爲y變量,類別爲x變量,因此您需要使用coord_flip來獲得水平條。

爲了避免coord_flip,您可以使用水平GEOM geom_barhggstance包,使free空間和尺度設置在facet_grid將工作:

library(ggplot2) 
library(ggstance) 

ggplot(data=mpg, aes(x=cty, y=model)) + 
    geom_barh(stat="identity") + 
    facet_grid(manufacturer ~ ., scales = "free_y", space = "free_y") 

注意,上面的代碼創建了一個堆疊條形圖,其中給定model的所有汽車的ctympg的值被堆疊在另一個的頂部,這是非感性的。例如,如果您在geom_barh內設置colour="green",則可以看到此內容。我認爲這個情節只是爲了說明,但我想指出這是完整的。

enter image description here

+0

我要建議'ggstance',謝謝你節省我的時間.. –

+1

那麼,@BenBolker,我認爲這是R社區的一項公共服務,因爲它可以讓你的時間更加重要,比如爲'lme4'增加新特性。 – eipi10

+0

感謝您的解釋和解決方案。是的,關於cty變量的好看。該示例僅用於說明。 – yake84