[英]create a manual legend for density plots in R (ggplot2)
我想在圖上添加圖例。 我在網上找到的所有解決方案都使用scale_color_manual-但這對我不起作用。 傳說在哪里? 這是我的代碼:
library(ggplot2)
ggplot() +
geom_density(aes(x = rnorm(100)), color = 'red') +
geom_density(aes(x = rnorm(100)), color = 'blue') +
xlab("Age") + ylab("Density") + ggtitle('Age Densities')
theme(legend.position = 'right') +
scale_color_manual(labels = c('first', 'second'), values = c('red', 'blue'))
您的數據格式不正確,您基本上是在一個普通的“畫布”上創建兩個單獨的圖,請參見下面的代碼(創建df
是至關重要的部分):
library(ggplot2)
df <- data.frame(
x = c(rnorm(100), runif(100)),
col = c(rep('blue', 100), rep('red', 100))
)
ggplot(df) +
geom_density(aes(x = x, color = col)) +
xlab("Age") + ylab("Density") + ggtitle('Age Densities') +
theme(legend.position = 'right') +
scale_color_manual(labels = c('first', 'second'), values = c('red', 'blue'))
如果出於某種原因您絕對需要兩個幾何來處理不同的數據源,則將color = XXX
部分移動到aes()
中,然后使用命名的矢量手動定義顏色:
ggplot() +
geom_density(aes(x = rnorm(100), color = 'first')) +
geom_density(aes(x = rnorm(100), color = 'second')) +
xlab("Age") + ylab("Density") + ggtitle('Age Densities') +
theme(legend.position = 'right') +
scale_color_manual(values = c('first' = 'red', 'second' = 'blue'))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.