![](/img/trans.png)
[英]Adjusting geom_bar (position=“dodge”) in ggplot
[英]geom_bar: dodge position with varied widths
我有兩個組的條形圖,其中y軸=獲得的美元,x軸的寬度=售出的單位數。 以下示例數據:
test<- structure(list(Person = c("Bob", "Bob", "Bob", "Bob", "Bob",
"Jim", "Jim", "Jim", "Jim", "Jim"), Car = c("Wombat", "Beetle",
"Impala", "Carrera", "Sienna", "Wombat", "Beetle", "Impala",
"Carrera", "Sienna"), tot = c(75090, 229994, 1229347, 247052,
1148873, 41114, 2430, 430423, 629812, 30442), freq = c(5L, 620L,
1324L, 219L, 550L, 36L, 1L, 213L, 195L, 2L)), .Names = c("Person",
"Car", "tot", "freq"), row.names = c(NA, 10L), class = "data.frame")
# Print bar chart.
ggplot()+
geom_bar(data=test,aes(x=reorder(Car,tot,function(x) -sum(x)),
y=as.numeric(tot)/1000,width=freq/1000,fill=Person),
stat='identity',position='identity')
我想對這張圖表做以下兩件事,但是遇到了障礙:
A)對於每個汽車類別,我都希望將人員並排放置,而不是彼此並排放置。 ggplot說我不能為不同長度的寬度position = 'dodge'
。
B)似乎汽車類別之間的間距是根據寬度最大的條設置的。 是否可以使間距以width * .05
類的方式變化? 例如,我想要Sienna
, Carrera
和Beetle
之間的空間更窄。
拆分這些圖表可能是一個更好的主意。 首先,您自己解決所有問題。 其次,您不會在同一軸上混合使用不同的變量(示例中的售出單位和汽車類別),從而避免了不良做法。
如果您堅持要按自己的方式繪制事物,那么,我想不出任何捷徑:ggplot會阻止其“非常規”用法。 這是最著名的示例: 繪制有2個y軸,一個y軸在左側,另一個y軸在右側的圖
library(gridExtra)
p1 <- ggplot()+
geom_bar(data=test,aes(x=reorder(Car,tot,function(x) -sum(x)),
y=tot/1000,fill=Person),
stat='identity',position='dodge')
p2 <- ggplot()+
geom_bar(data=test,aes(x=reorder(Car,tot,function(x) -sum(x)),
y=freq/1000,fill=Person),
stat='identity',position='dodge')
grid.arrange(p1, p2)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.