[英]How to create multiple plots, each with same plot area size, when only one plot has axis labels?
我想在1x3布局中繪制三個圖形。 只有第一個圖形需要有垂直軸標簽,但我希望所有三個繪圖區域的大小完全相同。 如果沒有或所有圖表都有軸標簽,這將沒有問題。 但是,當一個有軸標簽而另外兩個沒有時,如何讓所有三個圖形大小相同? 我試圖在基本圖形中執行此操作,因為這是我最熟悉的,但如果它們提供更好的方法來解決我的問題,我會很樂意使用grid或ggplot2。
這是一些假數據,我的繪圖代碼和情節本身:
# Fake Data
data = structure(list(y1 = 1:5, y2 = c(1.2, 2.4, 3.6, 4.8, 6), y3 = c(1.44,
2.88, 4.32, 5.76, 7.2)), .Names = c("y1", "y2", "y3"),
row.names = c("I needed 12 units for financial aid",
"I couldn't find any other open classes",
"I might be adding a major or minor",
"The class seemed interesting", "The class fit into my schedule"
), class = "data.frame")
# Plotting code
par(mar=c(5,15,4,1))
par(mfrow=c(1,3))
barplot(data$y1,names.arg=row.names(data), horiz=TRUE,las=1, +
xlim=c(0,8), main="Group 1")
par(mar=c(5,1,4,1))
barplot(data$y2,names.arg=row.names(data), horiz=TRUE,las=1, +
axisnames=FALSE, xlim=c(0,8), main="Group 2")
barplot(data$y3,names.arg=row.names(data), horiz=TRUE,las=1, +
axisnames=FALSE, xlim=c(0,8), main="Group 3")
# Reset plot options back to defaults
par(mfrow=c(1,1)
par(mar=c(5,4,4,2)+0.1)
[ 更新:我選擇了最直接回答我的問題的答案,這是基本圖形,但我建議同時查看其他解決方案,因為它們展示了如何在lattice
和ggplot2
做同樣的事情。
對於基本圖形,您希望使用外邊距而不是常規邊距。 只需用par(oma=c(0,15,0,0))
替換第一個par(mar=c(5,15,4,1))
par(oma=c(0,15,0,0))
並刪除對par
的第二個調用,並且繪圖將占用相等的空間(並且軸標簽將粘在左側的外邊距上)。
使用基本圖形的最簡單方法可能是使它們全部沒有y軸標簽,然后將標簽分別添加到所有三個標簽左側的附加面板中。
但是這樣的任務是為什么lattice
(和ggplot
,就此問題)被發明的原因之一。 你也可以考慮一個dotplot,特別是如果你是William Cleveland的粉絲。
library(reshape2)
d2 <- data
d2$q <- rownames(d2)
d2 <- melt(d2, measure.vars=1:3, id.vars=4)
d2$q <- factor(d2$q, levels=rownames(data))
library(lattice)
barchart(q ~ value|variable, data=d2)
dotplot(q ~ value|variable, data=d2)
我可以使用layout
某些東西拼湊在一起,但使用ggplot2的分面功能可以更快地完成它:
data$grp <- rownames(data)
datam <- melt(data,id.vars = "grp")
ggplot(datam,aes(x = grp,y = value)) +
facet_wrap(~variable,nrow = 1) +
geom_bar(stat = "identity") +
coord_flip()
擴展Greg Snow的答案(根據您的后續問題)這里是對代碼的最小編輯,使用基本圖形:
op <- par(oma=c(0,15,0,0), mfrow=c(1,3), mar=c(5,1,4,1))
barplot(data$y1,names.arg=row.names(data), horiz=TRUE,las=1, xlim=c(0,8), main="Group 1")
barplot(data$y2,names.arg=row.names(data), horiz=TRUE,las=1, axisnames=FALSE, xlim=c(0,8), main="Group 2")
barplot(data$y3,names.arg=row.names(data), horiz=TRUE,las=1, axisnames=FALSE, xlim=c(0,8), main="Group 3")
par(op)
避免你提到的“重置”的關鍵是在一次調用中將所有參數分配給par()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.