2015-05-29 174 views
2

我正在嘗試在條形圖的每個條上繪製分段,並使用ggplot2。我知道如何用連續的X軸來做到這一點,但不知道這個離散的軸。 我所做的是一種通過組成文本行的「黑客」。在ggplot2中向條形圖(離散x軸)添加分段

圖片看起來很不錯,但我沒有得到「限制」金屬濃度的圖例,並且最重要的是,每次放大或縮小時段的長度都會發生變化。

有誰知道哪個幾何可以實現這個更好? enter image description here

df = data.frame('metal'=c("Cu", "Fr", "Zn"), 'observed'=c(550, 60, 100), 'limit'=c(200, 150, 120)) 
ggplot(data=df) + aes(x=metal) + 
    geom_bar(aes(y=observed), stat="identity", fill="grey") + 
    geom_text(aes(y=limit, label="_____________"), size=rel(6), color="red") 

編輯:

的問題是接近this一個

+0

使用'geom_errorbar(AES(Y =極限,YMIN =極限,YMAX =極限))'HTTP改編:// stackoverflow.com/questions/30158225/how-to-add-a-horizo​​ntal-line-above-a-bar-chart-using-ggplot – scoa

+0

@scoa感謝它完美的作品。你有沒有關於如何獲得「極限」傳說的線索? – agenis

回答

1

this answer

ggplot(data=df) + aes(x=metal) + 
    geom_bar(aes(y=observed), stat="identity", fill="grey") + 
    geom_errorbar(aes(y=limit,ymin=limit,ymax=limit,colour="limit")) 

enter image description here

1

這是一種方法。

ggplot(data=df) + aes(x=metal) + 
    geom_bar(aes(y=observed), stat="identity", fill="grey", color = "grey60") + 
    geom_bar(data = df, aes(y=limit), stat="identity", fill="transparent", color = "grey30") + 
    geom_text(aes(y = limit +5), label = df$limit) 

enter image description here

+0

(+1)thanks @lawyeR這是一個非常明亮的建議,顯示限制矩形。我想接受這兩個答案,但是scoa的答案與最初的請求最接近並顯示我的傳奇。 – agenis