How can I change legend labels in ggplot?
You can do that via the labels=
argument in a scale_color_*()
function by supplying a named vector. Here's an example:
library(ggplot2)
set.seed(1235)
df <- data.frame(x=1:10, y=1:10, z = sample(c("Control", "B", "C"), size=10, replace=TRUE))
df$z <- factor(df$z, levels=c("Control", "B", "C")) # setting level order
p <- ggplot(df, aes(x,y, color=z)) + geom_point(size=4)
p
To change the name of "Control" totally "in plot code", I'll use scale_color_hue(labels=...)
. Note that by default, ggplot2
uses an evenly-spaced hue scaling, so this keeps the colors themselves the same. Using a named vector is not required, but a good idea to ensure you don't have mixing up of names/labels:
p + scale_color_hue(labels=c("Control" = "A", "B"="B", "C"="C"))
How to change legend title in ggplot
This should work:
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"))
(or alternatively)
p + scale_fill_discrete(name = "New Legend Title")
How I do manually change the key labels values in a legend in ggplot2?
Thanks for you help Slowlearner. I just fixed the code with your commentaries. I could fix the code using melt()
function at the beginning and scale_linetype_maunual
into the code. Here is the new code.
library(reshape)
intactos2 <- melt(intactos, id.var = c("ecd","ACTIVIDAD"))
a <- ggplot(intactos2,aes(y = value, x= ecd,group=ACTIVIDAD))+
geom_line(aes(colour = ACTIVIDAD,linetype=ACTIVIDAD),colour='black',size=0.5)+
scale_linetype_manual("Glaciares rocosos",
breaks=c("1","2"),
values=c("solid","dashed"),
labels = c("Activos", "Inactivos"))+
ylab("Altitud m") +
xlab("Distribucion Acumulada (%)\n")+
scale_y_continuous(limits=c(3500,5000),
breaks=c(3500,3750,4000,4250,4500,4750,5000))+
scale_x_continuous(limits = c(0.00, 1.00),
breaks = seq(0, 1, 0.1),
labels=seq(0,100,10))+
theme( plot.background = element_rect(fill="white")
,panel.background = element_rect(fill='white')
,panel.grid.major = element_line(colour = 'grey', linetype = 'dotted',size=0.5)
,panel.grid.minor = element_line(colour = 'white', linetype = 'dashed')
,panel.border = element_blank()
,axis.line = element_line(colour = 'black')
,axis.text.x=element_text(colour="black")
,axis.text.y=element_text(colour="black")
,panel.grid.major =element_line(colour = 'grey', linetype = 'dashed')
,legend.key=element_rect(fill="white",colour="white"),legend.position=c(0.3,0.8))+
geom_hline(aes(yintercept=4000),linetype="solid",size = 0.5)
a
a + annotate("text",label="0°C MAAT isoterma",x=0.8,y=4050,size=4)
Here the plot that I finally got! https://dl.dropbox.com/u/11320858/plot3.png
Editing legend (text) labels in ggplot
The tutorial @Henrik mentioned is an excellent resource for learning how to create plots with the ggplot2
package.
An example with your data:
# transforming the data from wide to long
library(reshape2)
dfm <- melt(df, id = "TY")
# creating a scatterplot
ggplot(data = dfm, aes(x = TY, y = value, color = variable)) +
geom_point(size=5) +
labs(title = "Temperatures\n", x = "TY [°C]", y = "Txxx", color = "Legend Title\n") +
scale_color_manual(labels = c("T999", "T888"), values = c("blue", "red")) +
theme_bw() +
theme(axis.text.x = element_text(size = 14), axis.title.x = element_text(size = 16),
axis.text.y = element_text(size = 14), axis.title.y = element_text(size = 16),
plot.title = element_text(size = 20, face = "bold", color = "darkgreen"))
this results in:
As mentioned by @user2739472 in the comments: If you only want to change the legend text labels and not the colours from ggplot's default palette, you can use scale_color_hue(labels = c("T999", "T888"))
instead of scale_color_manual()
.
Change the symbol in a legend key in ggplot2
Adapting code for this answer:
The idea is to inhibit the geom_text
legend, but to allow a legend for geom_point
, but make the point size zero so the points are not visible in the plot, then set size and shape of the points in the legend in the guides
statement
x <- rnorm(9); y <- rnorm(9); s <- rep(c("F","G","K"), each = 3)
df <- data.frame(x, y, s)
#
require(ggplot2)
#
ggplot(df, aes(x = x, y = y, colour = s, label = s)) +
geom_point(size = 0, stroke = 0) + # OR geom_point(shape = "") +
geom_text(show.legend = FALSE) +
guides(colour = guide_legend(override.aes = list(size = 5, shape = c(utf8ToInt("F"), utf8ToInt("K"), utf8ToInt("G"))))) +
scale_colour_discrete(name = "My name", breaks = c("F","K","G"), labels = c("Fbig","Kbig","Gbig"))
Changing Legend Items ggplot
You can use scale_colour_gradient
to set breaks
, then change the labels
.
library(tidyverse)
ggplot() +
geom_line(data=mtcars,
aes(x=cyl, y = mpg,
color=mpg)) +
scale_colour_gradient(breaks = c(15, 20, 25, 30, 40),
labels = c("1+", "2+", "3+", "4+", "5+"))
Output
Format of key label text in legend in ggplot
Try the following:
scale_fill_distiller(name=expression(Confirmed~(log[10])),
palette = "Spectral", trans = "log10",
breaks = breaks_vec,
labels = parse(text=c("1","10","100","1000","10^4","10^5"))) +
guides(fill=guide_legend(title=expression(Confirmed~(log[10]))))
How can I change the title of a ggplot2 legend?
Add
+ labs(colour = "legend title")
to your ggplot call.
Great resource site is also google group for ggplot2.
edit: this assumes that colour is the aesthetic in the legend, e.g. qplot(x,y,colour=z)
. If another aesthetic is being shown in the legend, use that as the argument instead, e.g. + labs(fill = "legend title")
for a raster/image plot.
More generally, if you specify an explicit scale such as scale_colour_continuous
, you can set the scale_name
argument (warning: the details of the arguments to scales may have changed in recent releases of ggplot2
; this description is of version 0.9.2.1).
Related Topics
Making Plot Functions with Ggplot and Aes_String
Two Horizontal Bar Charts with Shared Axis in Ggplot2 (Similar to Population Pyramid)
Plotting Ordiellipse Function from Vegan Package Onto Nmds Plot Created in Ggplot2
Overlay Geom_Points() on Geom_Boxplot(Fill=Group)
Calculating Peaks in Histograms or Density Functions
How to Calculate Any Negative Number to the Power of Some Fraction in R
How to Convert Certain Columns Only to Numeric
Get Monthly Means from Dataframe of Several Years of Daily Temps
Is There a Predict Function for Plm in R
Reading Big Data with Fixed Width
Harnessing .F List Names with Purrr::Pmap
Grouping Every N Minutes with Dplyr
Add Text on Right of Shinydashboard Header
How to Access Dimensions of Labels Plotted by 'Geom_Text' in 'Ggplot2'
Calling a User-Defined R Function from C++ Using Rcpp
Extend an Irregular Sequence and Add Zeros to Missing Values