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()
.
The legend titles can be labeled by specific aesthetic.
This can be achieved using the guides()
or labs()
functions from ggplot2
(more here and here). It allows you to add guide/legend properties using the aesthetic mapping.
Here's an example using the mtcars
data set and labs()
:
ggplot(mtcars, aes(x=mpg, y=disp, size=hp, col=as.factor(cyl), shape=as.factor(gear))) +
geom_point() +
labs(x="miles per gallon", y="displacement", size="horsepower",
col="# of cylinders", shape="# of gears")
Answering the OP's question using guides()
:
# transforming the data from wide to long
require(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") +
scale_color_manual(labels = c("T999", "T888"), values = c("blue", "red")) +
theme_bw() +
guides(color=guide_legend("my title")) # add guide properties by aesthetic