[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


Questions with r tag:

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? Saving a high resolution image in R Change bar plot colour in geom_bar with ggplot2 in r Converting data frame column from character to numeric Extract Month and Year From Date in R How to combine two lists in R Extract year from date Ifelse statement in R with multiple conditions R dplyr: Drop multiple columns Remove legend ggplot 2.2 Remove all of x axis labels in ggplot how to remove multiple columns in r dataframe? Aggregate multiple columns at once Changing fonts in ggplot2 How to specify "does not contain" in dplyr filter how to use the Box-Cox power transformation in R Convert dataframe column to 1 or 0 for "true"/"false" values and assign to dataframe Having trouble setting working directory Coerce multiple columns to factors at once How to declare a vector of zeros in R Create empty data frame with column names by assigning a string vector? Explain ggplot2 warning: "Removed k rows containing missing values" R for loop skip to next iteration ifelse Error: package or namespace load failed for ggplot2 and for data.table How do I change the default library path for R packages Select first and last row from grouped data R * not meaningful for factors ERROR Error: could not find function "%>%" Raise to power in R In R, dealing with Error: ggplot2 doesn't know how to deal with data of class numeric Error - replacement has [x] rows, data has [y] Merge r brings error "'by' must specify uniquely valid columns" Non-numeric Argument to Binary Operator Error in R Convert row names into first column Append data frames together in a for loop Plotting with ggplot2: "Error: Discrete value supplied to continuous scale" on categorical y-axis R Markdown - changing font size and font type in html output Replace all occurrences of a string in a data frame How to convert dataframe into time series? Sum across multiple columns with dplyr Removing NA observations with dplyr::filter()

Questions with text tag:

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 Setting a max character length in CSS Android EditText view Floating Hint in Material Design Difference between VARCHAR and TEXT in MySQL Editing legend (text) labels in ggplot Extracting text OpenCV Input type "number" won't resize How to display text in pygame? How can I use a batch file to write to a text file? Basic text editor in command prompt? How to count the number of words in a sentence, ignoring numbers, punctuation and whitespace? How to remove text before | character in notepad++ how to customise input field width in bootstrap 3 How to set text size in a button in html How do I append text to a file? Writing new lines to a text file in PowerShell How to read existing text files without defining path How to place Text and an Image next to each other in HTML? Changing background color of text box input not working when empty Indent starting from the second line of a paragraph with CSS Align text to the bottom of a div How do I find all files containing specific text on Linux? Find specific string in a text file with VBS script How to convert text column to datetime in SQL Output grep results to text file, need cleaner output Javascript change color of text and background to input value Using BufferedReader to read Text File Saving a text file on server using JavaScript Java: print contents of text file to screen How to add text to an existing div with jquery Making text background transparent but not text itself How to center a <p> element inside a <div> container? How to read a text file into a list or an array with Python Matplotlib scatter plot with different text at each data point Text on image mouseover? how to align text vertically center in android How to read text file in JavaScript Text border using css (border around text) How to remove non UTF-8 characters from text file How to print Two-Dimensional Array like table Read a text file in R line by line

Questions with ggplot2 tag:

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 Plotting with ggplot2: "Error: Discrete value supplied to continuous scale" on categorical y-axis ggplot2, change title size How can I change the Y-axis figures into percentages in a barplot? ggplot2 line chart gives "geom_path: Each group consist of only one observation. Do you need to adjust the group aesthetic?" What does the error "arguments imply differing number of rows: x, y" mean? How to plot a function curve in R Reorder bars in geom_bar ggplot2 by value ggplot geom_text font size control Editing legend (text) labels in ggplot How to get a barplot with several variables side by side grouped by a factor Stacked bar chart How to combine 2 plots (ggplot) into one plot? increase legend font size ggplot2 Stacked Bar Plot in R Persistent invalid graphics state error when using ggplot2 Aesthetics must either be length one, or the same length as the dataProblems Plotting multiple time series on the same plot using ggplot() Boxplot show the value of mean Subset and ggplot2 Grouped bar plot in ggplot Setting individual axis limits with facet_wrap and scales = "free" in ggplot2 R: "Unary operator error" from multiline ggplot2 command Eliminating NAs from a ggplot Plot multiple lines in one graph Construct a manual legend for a complicated plot Plot data in descending order as appears in data frame How to deal with "data of class uneval" error from ggplot2? Adding a regression line on a ggplot Label points in geom_point Change size of axes title and labels in ggplot2 How to change line width in ggplot? remove legend title in ggplot How to change legend title in ggplot Plot multiple boxplot in one graph Turning off some legends in a ggplot Increase distance between text and title on the y-axis Fixing the order of facets in ggplot R Plotting confidence bands with ggplot Force the origin to start at 0 Add a common Legend for combined ggplots

Questions with label tag:

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 matplotlib: colorbars and its text labels How can I label points in this scatterplot? how to make label visible/invisible? css label width not taking effect adding x and y axis labels in ggplot2 matplotlib set yaxis label size Set Text property of asp:label in Javascript PROPER way How can I add a hint or tooltip to a label in C# Winforms? Transparent control over PictureBox text-align: right; not working for <label> How to set top-left alignment for UILabel for iOS application? How to calculate UILabel height dynamically? Get text of label with jquery pyplot axes labels for subplots How to create a checkbox with a clickable label? How do I set an ASP.NET Label text from code behind on page load? How can I wrap text in a label using WPF? C# How to change font of a label Change label text using JavaScript Forcing label to flow inline with input that they label How to change the text of a label? HTML checkbox onclick called in Javascript Get values from label using jQuery How do I set the colour of a label (coloured text) in Java? c# .net change label text How can I control the width of a label tag? How to hide element label by element id in CSS? Update Tkinter Label from variable rotating axis labels in R Changing button color programmatically Using "label for" on radio buttons Rotating and spacing axis labels in ggplot2 Word wrap for a label in Windows Forms How to create a label inside an <input> element? Find html label associated with a given input