[r] Editing legend (text) labels in ggplot

I have spent hours looking in the documentation and on StackOverflow, but no solution seems to solve my problem. When using ggplot I can't get the right text in the legend, even though it's in my dataframe. I have tried scale_colour_manual, scale_fill_manual with different values for labels= such as c("T999", "T888")", "cols".

Here is my code:

T999 <- runif(10, 100, 200)
T888 <- runif(10, 200, 300)
TY <- runif(10, 20, 30)
df <- data.frame(T999, T888, TY)


ggplot(data = df, aes(x=T999, y=TY, pointtype="T999")) + 
       geom_point(size = 15, colour = "darkblue") + 
       geom_point(data = df, aes(x=T888, y=TY), colour = 'red', size = 10 ) + 
       theme(axis.text.x = element_text(size = 20), axis.title.x =element_text(size = 20),   axis.text.y = element_text(size = 20)) +
       xlab("Txxx") + ylab("TY [°C]") + labs(title="temperatures", size = 15) + 
       scale_colour_manual(labels = c("T999", "T888"), values = c("darkblue", "red")) +    theme(legend.position="topright")

Help would be very appreciated!

This question is related to r text ggplot2 label

The answer is


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:

enter image description here

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")

enter image description here

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

enter image description here


Examples related to r

How to get AIC from Conway–Maxwell-Poisson regression via COM-poisson package in R? R : how to simply repeat a command? session not created: This version of ChromeDriver only supports Chrome version 74 error with ChromeDriver Chrome using Selenium How to show code but hide output in RMarkdown? remove kernel on jupyter notebook Function to calculate R2 (R-squared) in R Center Plot title in ggplot2 R ggplot2: stat_count() must not be used with a y aesthetic error in Bar graph R multiple conditions in if statement What does "The following object is masked from 'package:xxx'" mean?

Examples related to text

Difference between opening a file in binary vs text How do I center text vertically and horizontally in Flutter? How to `wget` a list of URLs in a text file? Convert txt to csv python script Reading local text file into a JavaScript array Python: How to increase/reduce the fontsize of x and y tick labels? How can I insert a line break into a <Text> component in React Native? How to split large text file in windows? Copy text from nano editor to shell Atom menu is missing. How do I re-enable

Examples related to ggplot2

Center Plot title in ggplot2 R ggplot2: stat_count() must not be used with a y aesthetic error in Bar graph Saving a high resolution image in R Change bar plot colour in geom_bar with ggplot2 in r Remove legend ggplot 2.2 Remove all of x axis labels in ggplot Changing fonts in ggplot2 Explain ggplot2 warning: "Removed k rows containing missing values" Error: package or namespace load failed for ggplot2 and for data.table In R, dealing with Error: ggplot2 doesn't know how to deal with data of class numeric

Examples related to label

How to set label size in Bootstrap How do I change the text size in a label widget, python tkinter Change grid interval and specify tick labels in Matplotlib Editing legend (text) labels in ggplot How to change Label Value using javascript React ignores 'for' attribute of the label element How to dynamically update labels captions in VBA form? why I can't get value of label with jquery and javascript? What does "for" attribute do in HTML <label> tag? Get Application Name/ Label via ADB Shell or Terminal