![](/img/trans.png)
[英]How to change legend title and key order and colour to a multi-stacked barplot in R with ggplot2
[英]Does anyone know why the title of my legend isn't updating? (ggplot2, stacked barplot)
出於某種原因,盡管在代碼塊中所有不同的可能位置添加了 +labs(fill = "Survival status"),但我無法將圖例的標題從“surv_status”(變量名)更新為“Survival Status” .
有什么建議么? 謝謝!
ggplot(data_train, aes(x = axil_nodes, fill = as.factor(surv_status))) +
geom_bar(position = "fill") +
labs(fill = "Survival status") +
theme_classic() +
xlab("Number of positive axillary nodes") +
ggtitle("Visualizing positive axillary node count by survival status") +
theme(legend.background = element_rect(color = "black", linetype = "dashed")) +
scale_fill_discrete(name = "surv_status", labels = c("Survived", "Deceased"))
您可以使用幾種不同的方法來更改帶有ggplot2
的圖例的標題。 我知道三個我的頭頂:
使用labs(fill= "Legend Title")
,其中fill
可以替換為與圖例相關的任何美學修飾符。
使用scale_*_**()
函數和name=
參數。 例如, scale_color_discrete(name="Legend Title")
使用guides()
並在其中一個guide
函數中聲明title=
。 例如, guides(shape=guide_legend(title="Legend Title"))
如果您使用多種方法解決標題,則優先級為:
guides()
方法scale_*_**()
方法labs()
方法aes()
function 中指定的列的名稱。 所以下面的例子清楚地表明了這一點。 您可以移動對gg
object 的每個引用,但優先級似乎保持不變。 plot 中的最終圖例與以下代碼的任何順序將導致根據guides()
命名圖例。
ggplot(df, aes(x,y, color=z)) + geom_point() +
guides(color=guide_legend(title='My other other legend')) +
scale_color_discrete(name='My Legend') +
labs(color='My other Legend')
如果我刪除guides()
部分,圖例名稱現在反映scale_color_discrete()
:
ggplot(df, aes(x,y, color=z)) + geom_point() +
scale_color_discrete(name='My Legend') +
labs(color='My other Legend')
在您的示例中,您有labs(fill = "Survival status")
和scale_fill_discrete(name = "surv_status"...
。使用上述規則,您應該了解更改labs()
function 永遠不會優先於scale_fill_discrete()
. 您可以從scale_fill_discrete()
中刪除name
的參數,也可以在scale_fill_discrete()
() 中更改name=
的值,以更改您的圖例標題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.