2014-01-28 131 views
5

我正在從AESRD 2013 - SCO Bitumen - 7y.csvin this folder生成ggplot2線圖。該文件根據我的意願在網站上自動創建。這些是幾個時間序列,顯示了一些生產值,每個值根據「彙編」欄命名。所以我按照「彙編」分組。ggplot2:按照字母順序排列而不是按照數據集中外觀的順序排列

看到我的代碼在文件plotter.r的摘錄可在同一文件夾中(見上文)。

# "dt" is the dataframe derived from the csv file. 
# "thinned" is some vector of x-values that tells where to draw the special symbols. 

p = ggplot(dt, aes(Date, Value, colour= Compilation, group = Compilation, size = plotParameter), guide=FALSE) 
p = p + geom_point(data=dt[thinned,],aes(as.Date(Date), Value, colour= Compilation, shape = Compilation), size = 5) 
p = p + scale_shape_manual(values = seq(0,20)) 
p = p + geom_line(guide = FALSE) 
p = p + scale_colour_manual(values=cbPalette) #cbPalette is already defined 
p = p + scale_size(range=c(0.5, 2), guide=FALSE) 
p = p + scale_y_continuous(labels = comma) 
p = p + ylab("Barrels per day") + xlab("") 
p = p + theme(legend.text = element_text(size = 8, hjust = 5, vjust= -5)) 
plot(p) 

來了討厭的事:圖例重新排序我的合輯字母enter image description here

我特意設計我的CSV文件,使每個編譯在一定的邏輯順序顯示出來(最重要的系列,然後再在一些性能參數的順序如下)。所以傳說的正確順序將根據unique(dt$Compilation)

我到現在爲止的步驟是將列Order引入到csv文件中,並試驗(不成功),並以各種方式更改我的代碼。沒有成功。

當然,我已經搜索並檢查了Stackoverflow上的大部分可用線程。我遇到了因式分解和重新排序,但我的彙編沒有「邏輯」順序,除了,它們出現在數據集中的順序。 *嘆氣*

任何人都可以點我在哪裏插入什麼

(獎勵點:如何擺脫象徵傳奇的水平線?)

+1

申請'breaks'兩個'scales'(scale_color_manual和scale_shape_manual)。如果我們只做了一個,它們就不會匹配,ggplot會將它們分成兩個傳說,而不是合併它們。 – RUser

+0

你解決了!如果你把它作爲答案(而不是評論)發佈,我可以用一些聲譽來獎勵你! – fridde

+0

剛剛在下面添加了答案 - 您可以繼續投票並將其批准爲答案 – RUser

回答

4

適用於breaks這兩個尺度(scale_color_manualscale_shape_manual)。如果我們這樣做只有一個,他們將不匹配,並且ggplot將它們分成兩個傳說,而不是將它們合併

就是這樣一個例子:

> library(ggplot2) 
> ggplot(mtcars, aes(wt, mpg, shape=factor(cyl))) + geom_point() + theme_bw() 
> library(ggplot2) 
> bp <- ggplot(data=PlantGrowth, aes(x=group, y=weight, fill=group)) + geom_boxplot() 
> bp 

enter image description here

bp + scale_fill_discrete(breaks=c("trt1","ctrl","trt2")) 

enter image description here

要反轉

也儘量

bp + scale_fill_discrete(breaks = unique(levels(PlantGrowth$group))) 
+0

也會探索用於圖例主題的'bp + opts(legend.key =)' – RUser

+0

有關'group'中項目出現的順序,此處的最後一行應爲:'bp + scale_fill_discrete(breaks = unique(PlantGrowth $ group))'? –

2

爲了解決順序:你可能想通過調用繪圖之前解決的dt$Compilation因子水平某物像dt <- transform(dt, Compilation=factor(Compilation, levels=unique(Compilation)))

說到水平線:你想要p = p + guides(size=FALSE)

相關問題