簡體   English   中英

在ggplot中顯示條形圖的圖例

[英]Show legend for bar plot in ggplot

如何顯示以下ggplot條形圖的圖例?

tmp <- data.frame(group = LETTERS[1:10], id = 10:1, a = runif(10), b = runif(10))

ggplot(tmp) + geom_bar(aes(x = reorder(group, id), a + b, group = 1), stat = 'identity')

更新:我有兩個圖表使用grid.arrangegridExtra 兩種圖表的條形數量相同,但其中的一條帶有圖例。 我以為,通過在第二張圖表中添加任何圖例,我將對齊條形(使兩個圖表的繪圖區域的寬度相同):

tmp <- data.frame(group = LETTERS[1:10], id = 10:1, 
                  a = runif(10), b = runif(10), c = rnorm(10))

p1 <- ggplot(tmp) + geom_bar(aes(x = reorder(group, id), c, fill = a), stat = 'identity')
p2 <- ggplot(tmp) + geom_bar(aes(x = reorder(group, id), a + b, group = 1), stat = 'identity')

library(gridExtra)

grid.arrange(p1, p2, heights = c(2, 1) )

現在,它看起來像這樣:

在此處輸入圖片說明

您可以為p2嘗試類似的操作,這將為底部圖形創建一個新圖例。

p2 <- ggplot(tmp) + geom_bar(aes(x = reorder(group, id), a + b, group = 1, fill = 0), stat = 'identity') +
    guides(fill=guide_legend(title="Title"))

這就是我所需要的

 guides(fill=guide_legend(title="Title"))

謝謝

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM