2012-05-31 95 views
45

我要繪製未使用的水平(即水平在計數爲0),在我的barplot,然而,未使用的水平下降了,我無法弄清楚如何讓他們GGPLOT2保持未使用的水平barplot

df <- data.frame(type=c("A", "A", "A", "B", "B"), group=rep("group1", 5)) 
df$type <- factor(df$type, levels=c("A","B", "C")) 

ggplot(df, aes(x=group, fill=type)) + geom_bar() 

在上面的例子,我想請參閱C標繪的計數爲0,但它是完全不存在......

感謝所有幫助 Ulrik合作

編輯:

這不會是我想要

df <- data.frame(type=c("A", "A", "A", "B", "B"), group=rep("group1", 5)) 
df1 <- data.frame(type=c("A", "A", "A", "B", "B", "A", "A", "C", "B", "B"), group=c(rep("group1", 5),rep("group2", 5))) 

df$type <- factor(df$type, levels=c("A","B", "C")) 
df1$type <- factor(df1$type, levels=c("A","B", "C")) 
df <- data.frame(table(df)) 

df1 <- data.frame(table(df1)) 

ggplot(df, aes(x=group, y=Freq, fill=type)) + geom_bar(position="dodge") 
ggplot(df1, aes(x=group, y=Freq, fill=type)) + geom_bar(position="dodge") 

猜解是用表()來計算頻率,然後繪製

回答

6

您需要設置滴= FALSE兩個尺度(填充和X)是這樣的:

library(ggplot2) 
df <- data.frame(type=c("A", "A", "A", "B", "B"), group=rep("group1", 5)) 
df1 <- data.frame(type=c("A", "A", "A", "B", "B", "A", "A", "C", "B", "B"), group=c(rep("group1", 5),rep("group2", 5))) 
df$type <- factor(df$type, levels=c("A","B", "C")) 
df1$type <- factor(df1$type, levels=c("A","B", "C")) 

plt <- ggplot(df, aes(x=type, fill=type)) + geom_bar(position='dodge') + scale_fill_discrete(drop=FALSE) + scale_x_discrete(drop=FALSE) 
plt1 <- ggplot(df1, aes(x=type, fill=type)) + geom_bar(position='dodge') + scale_fill_discrete(drop=FALSE) + scale_x_discrete(drop=FALSE) 

編輯:

我敢肯定,這個作品。忘了將x改爲鍵入而不是組和位置='閃避'!只需粘貼並測試。 stat_bin處理零計數的分箱。檢查docs

+0

我想這應該是OP的問題的答案。答案也會照顧圖例中的下降水平。 – SavedByJESUS

51

這是否你想要做什麼呢?

ggplot(df, aes(x=type)) + geom_bar() + scale_x_discrete(drop=FALSE) 

enter image description here

7

滴水平不起作用。在該圖上的第一個例子滴水平

library(ggplot2) 

df <- data.frame(type=c("A", "A", "A", "B", "B"), group=rep("group1", 5)) 
df$type <- factor(df$type, levels=c("A","B", "C")) 

ggplot(df, aes(x=group, fill=type)) + geom_bar(position="dodge") + scale_x_discrete(drop=FALSE) + scale_fill_discrete(drop=FALSE) 

結果:

enter image description here

解決的辦法是在第二示例中,其中頻率被手動計算:

df <- data.frame(type=c("A", "A", "A", "B", "B"), group=rep("group1", 5)) 
df1 <- data.frame(type=c("A", "A", "A", "B", "B", "A", "A", "C", "B", "B"), group=c(rep("group1", 5),rep("group2", 5))) 

df$type <- factor(df$type, levels=c("A","B", "C")) 
df1$type <- factor(df1$type, levels=c("A","B", "C")) 

df <- data.frame(table(df)) 
df1 <- data.frame(table(df1)) 

df$plot = "A" 
df1$plot = "B" 

df <- rbind(df, df1) 

ggplot(df, aes(x=group, y=Freq, fill=type)) + geom_bar(position="dodge", stat="identity") + facet_wrap(~ plot, scales="free") 

結果在此:

enter image description here

最後一個是最翔實的空間佔用按類別還有數= 0

0

,你也可以用「scale_fill_color」 例如:

plt <- ggplot(df, aes(x=type, fill=type)) + geom_bar(position='dodge') + scale_x_discrete(drop=FALSE)+ 
scale_fill_manual(
    values = c(
    "#ff6666", 
    "#cc9900", 
    "#cc9900", 
    ),drop=FALSE)