Cómo cambiar el título de la leyenda en ggplot
Tengo la siguiente parcela como a continuación. Fue creado con este comando:
library(ggplot2)
df <- data.frame(cond = factor(rep(c("A", "B"), each = 200)),
rating = c(rnorm(200), rnorm(200, mean=.8)))
ggplot(df, aes(x=rating, fill=cond)) +
geom_density(alpha = .3) +
xlab("NEW RATING TITLE") +
ylab("NEW DENSITY TITLE")
Ahora lo siguiente que quiero hacer es modificar el título de leyenda de cond a NUEVO TÍTULO DE LEYENDA.
Así que lo que hice fue simplemente agregar la siguiente línea agregar el final del código anterior:
+labs(colour="NEW LEGEND TITLE")
Pero no funciona. ¿Cuál es la forma correcta de hacerlo?
8 answers
Esto debería funcionar:
p <- ggplot(df, aes(x=rating, fill=cond)) +
geom_density(alpha=.3) +
xlab("NEW RATING TITLE") +
ylab("NEW DENSITY TITLE")
p <- p + guides(fill=guide_legend(title="New Legend Title"))
(o alternativamente)
p + scale_fill_discrete(name = "New Legend Title")
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-01-31 09:35:43
No profundicé mucho en esto, pero porque usaste fill=cond en ggplot(),
+ labs(color='NEW LEGEND TITLE')
Podría no haber funcionado. Sin embargo, reemplazar color por llenar, funciona!
+ labs(fill='NEW LEGEND TITLE')
Esto funcionó para mí en ggplot2_2.1.0
P.D. Habría comentado, pero mi reputación stackoverflow no es suficiente para comentar.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-14 03:04:40
Dado que tienes dos densidades, imagino que puedes querer establecer tus propios colores con scale_fill_manual
.
Si es así puedes hacer:
df <- data.frame(x=1:10,group=c(rep("a",5),rep("b",5)))
legend_title <- "OMG My Title"
ggplot(df, aes(x=x, fill=group)) + geom_density(alpha=.3) +
scale_fill_manual(legend_title,values=c("orange","red"))
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-01-31 09:39:55
Dado que en su código utilizó ggplot(data, fill= cond)
para crear el histograma, debe agregar el título de la leyenda utilizando también "fill" en la sección de etiqueta, es decir, +labs(fill="Title name")
. Si estaba utilizando un tipo diferente de gráfico donde el código era ggplot (data, colour= cond), entonces podría usar +labs(colour= "Title Name")
. En resumen, el argumento lab tiene que coincidir con el argumento aes.
He usado + guides(fill=guide_legend("my awesome title"))
para cambiar el título de la leyenda en los gráficos geom_bar, pero no parecía funcionar para geom_point.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-16 15:48:14
Ninguno de los códigos anteriores funcionó para mí.
Esto es lo que encontré y funcionó.
labs(color = "sale year")
También puede dar un espacio entre el título y la pantalla agregando \n
al final.
labs(color = 'sale year\n")
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-25 15:54:46
Hay otra respuesta muy simple que puede funcionar para algunos gráficos simples.
Simplemente agrega una llamada a guide_legend() en tu gráfico.
ggplot(...) + ... + guide_legend(title="my awesome title")
Como se muestra en el muy bonito ggplot docs.
Si eso no funciona, puede establecer con mayor precisión los parámetros de su guía con una llamada a guides :
ggplot(...) + ... + guides(fill=guide_legend("my awesome title"))
También puede variar la forma/color/tamaño especificando estos parámetros para su llamada a guides
también.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-24 15:59:22
Estoy usando un facet_wrap en mi ggplot y ninguna de las soluciones sugeridas funcionó para mí excepto la solución de ArnaudA:
qplot(…) + guides(color=guide_legend(title="sale year"))
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-20 11:24:52
También puede agregar una sola línea (última línea):
ggplot(df, aes(x=rating, fill=cond)) +
geom_density(alpha = .3) +
xlab("NEW RATING TITLE") +
ylab("NEW DENSITY TITLE") +
labs(fill = "Your Title")
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-21 19:43:25