2012-06-30 34 views
2

我在R中使用ggplot2繪製大量數據集。爲了使繪圖更易於比較,我設置了y尺度的極限,但事實證明, ,沒有任何東西繪製在劇情的「天然頂部」之上。ggplot2 - 缺少一些x-labes和網格線

例如,對於這個情節: Plot with missing labels and lines http://sickel.net/misc/output.png 我試圖設置頂部y值500(看着上方的空白,我已成功地),但如何讓ggplot還繪製標籤400,450和500以及相應的網格線?

數據在數據框df中分別與df $ dataset和df $ error一起作爲數據和錯誤級別。我的繪圖代碼目前是

max = max(df$dataset + df$error) * 1.05 
if(max > 300) max=505 

dataplot = ggplot(data=df, aes(x=species,y=dataset,fill=dim,ylim=c(0,max))) 
dataplot = dataplot+geom_bar(position=position_dodge()) 
dataplot = dataplot+scale_fill_manual(values=c("#BBBBBB", "#444444")) 
dataplot = dataplot + ylab(ylab) + xlab(xlab) + opts(legend.title=theme_blank()) 

limits <- aes(ymax = df$dataset+df$error, ymin=df$dataset-df$error) 
dodge = position_dodge(width=0.9) 

dataplot = dataplot + geom_errorbar(limits, position=dodge, width=0.5) 
dataplot = dataplot + opts(panel.background = theme_rect(fill='white', colour='white')) 
dataplot = dataplot + opts(panel.grid.major = theme_line(colour = "gray")) 

# dataplot = dataplot + coord_cartesian(ylim=c(0, max)) 
# dataplot = dataplot + scale_y_continuous(limits=c(0, max)) 

dataplot = dataplot + 
       opts(axis.text.x = theme_text(colour = "black",angle=90), 
        axis.text.y = theme_text(colour = "black")) 
dataplot = dataplot + opts(legend.key.size = unit(0.3, "cm")) 
print(dataplot) 

從上註釋掉線可以看出,我已經試過coord_cartesian,scale_y_continous以及本Y型LIM沒有任何的運氣(是的,我知道coord_cartesian被放大)

+0

'dataplot + ylim(0,max)'做你想要的嗎? – smillig

+0

抱歉無關的回覆,但無法找到聯繫電子郵件。從一個Clef到另一個Clerk(看我的標誌):你選擇什麼工具? –

+0

我可以肯定地告訴你,你在'aes'裏面使用'ylim'不會做你想做的事(並且永遠不會做任何有用的事情)。但是,如果你能提供一個可重複的例子,我認爲它會有所幫助。 – joran

回答

4

對於ylimits您可以添加:

+ scale_y_continuous(limits=c(0,500)) 

爲了設置刻度點,你可以使用:

breaks=seq(0, 500, 50) # which means ticks from 0-500, every 50 units 

因此,我認爲你需要添加下面的代碼到你的陰謀代碼:

+scale_y_continuous(limits=c(0,500),breaks=seq(0, 500, 50)) 
+1

我會很好奇OP對這個答案的評價,因爲他們的問題特別指的是嘗試了設置'scale_y_continuous(limits = ...)'並且它不起作用。 – joran

+0

嗨喬蘭...我尊重你的意見,但我不同意你的看法。我提到你在這個問題中的這句話:「...如何使ggplot也繪製400,450和500的標籤和相應的網格線?」 – Sam

+0

我想你誤解了我的評論。這並不意味着暗示你錯了,或者你應該刪除你的答案。我的觀點是,OP的代碼很不清楚,因爲它不具有可重複性,所以不可能判斷這個答案是否有用。很可能,誰知道。如果OP_has_實際上嘗試了'scale_y_continuous(limits = c(0,500))',他們明確表示他們已經嘗試過了,那麼它們的繪圖將遠遠超出問題中當前顯示的內容。 – joran

1

對我來說,無論是使用ylim(0, max)scale_y_continuous(limits=c(0, max),breaks=seq(0, max, 50))作品我想你想要的方式。例如,使用diamonds數據:

library(ggplot2) 
data(diamonds) 
(p <- ggplot(diamonds, aes(clarity, fill=cut)) + geom_bar(position="dodge")) 
max.y <- 10000 
p + ylim(0, max.y) 
p + scale_y_continuous(limits=c(0, max.y), breaks=seq(0, max.y, 1000)) 

我得到以下三個圖。第一個是沒有設置y軸,第二個使用ylim(),第三個使用scale_y_continuous()。我希望這有幫助!

enter image description here

+0

你是對的,這正是我想要的。我一定弄錯了某個地方的東西。謝謝。 – MortenSickel