इस प्रश्न को question की खोज करके प्रेरित किया जाता है। स्वीकार किए गए समाधान के साथ समस्या अधिक स्पष्ट हो जाती है जब प्रति पहलू बार की संख्या में अधिक असमानता होती है। कि समाधान का उपयोग इस डेटा पर एक नज़र और उसके एवज में भूखंड लें:ggplot2 + gridExtra: विभिन्न आकार प्लॉट grobs में geom_bar को कैसे सुनिश्चित करें सटीक समान बार चौड़ाई
# create slightly contrived data to better highlight width problems
data <- data.frame(ID=factor(c(rep(1,9), rep(2,6), rep(3,6), rep(4,3), rep(5,3))),
TYPE=factor(rep(1:3,length(ID)/3)),
TIME=factor(c(1,1,1,2,2,2,3,3,3,1,1,1,2,2,2,1,1,1,2,2,2,1,1,1,1,1,1)),
VAL=runif(27))
# implement previously suggested solution
base.width <- 0.9
data$w <- base.width
# facet two has 3 bars compared to facet one's 5 bars
data$w[data$TIME==2] <- base.width * 3/5
# facet 3 has 1 bar compared to facet one's 5 bars
data$w[data$TIME==3] <- base.width * 1/5
ggplot(data, aes(x=ID, y=VAL, fill=TYPE)) +
facet_wrap(~TIME, ncol=1, scale="free") +
geom_bar(position="stack", aes(width = w),stat = "identity") +
coord_flip()
आप चौड़ाई बिल्कुल सही लग रही है पर ध्यान देंगे, लेकिन पहलू 3 में खाली स्थान के काफी स्पष्ट है। Ggplot2 में इसे ठीक करने का कोई आसान तरीका नहीं है जिसे मैंने अभी तक देखा है (facet_wrap में space
विकल्प नहीं है)।
# create each of the three plots, don't worry about legend for now
p1 <- ggplot(data[data$TIME==1,], aes(x=ID, y=VAL, fill=TYPE)) +
facet_wrap(~ TIME, ncol=1) +
geom_bar(position="stack", show_guide=FALSE) +
coord_flip()
p2 <- ggplot(data[data$TIME==2,], aes(x=ID, y=VAL, fill=TYPE)) +
facet_wrap(~ TIME, ncol=1) +
geom_bar(position="stack", show_guide=FALSE) +
coord_flip()
p3 <- ggplot(data[data$TIME==3,], aes(x=ID, y=VAL, fill=TYPE)) +
facet_wrap(~ TIME, ncol=1) +
geom_bar(position="stack", show_guide=FALSE) +
coord_flip()
# use similar arithmetic to try and get layout correct
require(gridExtra)
heights <- c(5, 3, 1)/sum(5, 3, 1)
print(arrangeGrob(p1 ,p2, p3, ncol=1,
heights=heights))
आप मैं एक ही गणित पहले से सुझाव पर आधारित पहलू प्रति बार की संख्या का इस्तेमाल किया पर ध्यान देंगे, लेकिन इस में:
अगला चरण इस gridExtra का उपयोग कर हल करने का प्रयास करने के लिए है अगर यह बहुत गलत हो जाता है। ऐसा लगता है क्योंकि अतिरिक्त "निरंतर ऊंचाई" तत्व हैं जिन्हें मुझे गणित में विचार करने की आवश्यकता है।
एक और जटिलता (मुझे विश्वास है) यह है कि अंतिम आउटपुट (और चौड़ाई मैच चाहे या नहीं) यह भी चौड़ाई और ऊंचाई पर निर्भर करेगा जहां मैं अंतिम ग्रोब आउटपुट कर रहा हूं, चाहे वह आर/आरस्टूडियो में हो पर्यावरण, या एक पीएनजी फ़ाइल के लिए।
मैं यह कैसे पूरा कर सकते हैं?
साथ 'ggplot_build' आप सीधे अपने पहले समाधान में प्रत्येक पैनल की ऊंचाई को संशोधित कर सकता है। कोहस्के ने यहां उदाहरण पोस्ट किए हैं – baptiste
@baptiste धन्यवाद, जल्द ही एक नज़र डालें और अपडेट करें –