Editing legend (text) labels in ggplot - r

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!

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

Related

Add an additional legend according to the colors of x axis labels

I have modified the colors of my x axis labels according to their group.
For that, I have used the following pseudocode:
library(ggsci)
library(ggplot2)
x_cols = pal_jco()(length(unique(melted_df$Group)))
names(x_cols) = unique(melted_df$Group)
ggplot(melted_df, ... + theme(axis.text.x = element_text(colour = x_cols))
I would like to add a legend to the plot (if possible, outside the plot), that explains the colouring of the x axis labels.
melted_df dataframe looks like this:
Here the full code:
#Generate color mapping
x_cols = pal_jco()(length(unique(melted_df$Group)))
names(x_cols) = unique(melted_df$Group)
melted_df$mycolors = sapply(as.character(melted_df$Group), function(x) x_cols[x])
#Plot
ggplot(melted_df, aes(fill=variable, y=value, x=fct_inorder(id))) +
geom_bar(position="stack", stat = "identity") + ggtitle("Barplot") +
theme_bw() +
xlab("samples") + ylab("Counts") +
theme(axis.title.y=element_text(size=10), axis.title.x=element_text(size=10),
plot.title = element_text(face = "bold", size = (15), hjust = 0.5),
axis.text.x = element_text(distinct(samples_melt[c("id", "mycolors")])$mycolors)) +
guides(fill=guide_legend(title="Columns"))
In the absence of a reproducible example, here is how you might do it with the built-in iris data set:
library(ggplot2)
ggplot(iris, aes(Species, Sepal.Length)) +
stat_summary(fun = mean, geom = "col", aes(fill = Species)) +
geom_point(aes(color = Species), alpha = 0, key_glyph = draw_key_text) +
theme_bw(base_size = 20) +
labs(color = "") +
guides(color = guide_legend(override.aes = list(alpha = 1, size = 8))) +
theme(axis.text.x = element_text(color = scales::hue_pal()(3), face = 2))
I addressed the issue using Legend() constructor, provided by ComplexHeatmap library.
I first used the code provided above under the EDIT section, and then I added the following code in order to draw an additional legend explaining the x-axis colouring.
lgd = Legend(labels = names(x_cols), title = "Group", labels_gp = gpar(fontsize = 8), nrow = 1, legend_gp = gpar(fill = x_cols))
draw(lgd, x = unit(1.8, "cm"), y = unit(0.3, "cm"), just = c("left", "bottom"))

How do i change the legend label on ggplot, geom_point? [duplicate]

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!
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

Draw heatmap for a matrix using circle in R [duplicate]

Is it possible to draw a heatmap with circles instead of square in ggplot2? It would be neat to not only represent the values by a color gradient but also by the circle size.
I am thinking of a graph like this dot heatmap where also the circle sizes are alternated by their specific value. I already read myself into heatmapping with ggplot2 but couldn't find a solution. For heatmapping I alternated the example posted on learnr.wordpress.com to:
library(ggplot2)
library(plyr)
library(reshape2)
library(scales)
kreuz <- read.csv("http://datasets.flowingdata.com/ppg2008.csv")
kreuz.m <- melt(kreuz)
(p <- ggplot(kreuz.m, aes(Name, variable)) +
geom_tile(aes(fill = value), colour = "white") +
scale_fill_gradient2(breaks=waiver(), name="binding strength",
low ="white", mid= ("lightblue"), high = "steelblue", midpoint = 4))
base_size <- 10
p + theme_grey(base_size = base_size) +
theme(panel.grid.major = element_blank())+
labs(x = "Patient ID", y = "Phage Motives", title = "Cross Reactivity")+
scale_x_discrete(expand = c(0, 0)) +
scale_y_discrete(expand = c(0, 0)) +
theme(legend.position = "right", axis.ticks = element_blank(),
axis.text.x = element_text(size = base_size *0.8, angle = 270, hjust = 0,
colour = "grey50"))+
labs(x = "Patient ID", y = "Phagemotives", title = "cross reactivity")
I would be very greatful for some hints!
In this example size and colour both correspond with the variable value because it's the only variable numeric available in the kreuz.m dataset.
ggplot(kreuz.m, aes(Name, variable)) +
geom_point(aes(size = value, colour=value))

Is a heatmap in "sized dot style" possible in ggplot2?

Is it possible to draw a heatmap with circles instead of square in ggplot2? It would be neat to not only represent the values by a color gradient but also by the circle size.
I am thinking of a graph like this dot heatmap where also the circle sizes are alternated by their specific value. I already read myself into heatmapping with ggplot2 but couldn't find a solution. For heatmapping I alternated the example posted on learnr.wordpress.com to:
library(ggplot2)
library(plyr)
library(reshape2)
library(scales)
kreuz <- read.csv("http://datasets.flowingdata.com/ppg2008.csv")
kreuz.m <- melt(kreuz)
(p <- ggplot(kreuz.m, aes(Name, variable)) +
geom_tile(aes(fill = value), colour = "white") +
scale_fill_gradient2(breaks=waiver(), name="binding strength",
low ="white", mid= ("lightblue"), high = "steelblue", midpoint = 4))
base_size <- 10
p + theme_grey(base_size = base_size) +
theme(panel.grid.major = element_blank())+
labs(x = "Patient ID", y = "Phage Motives", title = "Cross Reactivity")+
scale_x_discrete(expand = c(0, 0)) +
scale_y_discrete(expand = c(0, 0)) +
theme(legend.position = "right", axis.ticks = element_blank(),
axis.text.x = element_text(size = base_size *0.8, angle = 270, hjust = 0,
colour = "grey50"))+
labs(x = "Patient ID", y = "Phagemotives", title = "cross reactivity")
I would be very greatful for some hints!
In this example size and colour both correspond with the variable value because it's the only variable numeric available in the kreuz.m dataset.
ggplot(kreuz.m, aes(Name, variable)) +
geom_point(aes(size = value, colour=value))

ggplot2 - How to boxplot two variables with different scales on same plot using a primary and secondary y-axis?

Datalink:
Data
Code:
distevyield <- read.csv(file = "F:/Purdue University/RA_Position/PhD_ResearchandDissert/PhD_Draft/GTAP-CGE/GTAP_NewAggDatabase/NewFiles/GTAP_DistEVYield.csv", header=TRUE, sep=",", na.string="NA", dec=".", strip.white=TRUE)
str(distevyield)
distevyield <- as.data.frame(distevyield)
distevyield[5:6] <- sapply(distevyield[5:6],as.numeric)
distevyield <- droplevels(distevyield)
distevyield <- transform(distevyield,region=factor(region,levels=unique(region)))
library(ggplot2)
distevyield.f <- melt(subset(distevyield, region !="World"))
Figure3 <- ggplot(data = distevyield.f, aes(factor(variable), value))
Figure3 + geom_boxplot() +
theme(axis.text.x = element_text(colour = 'black', angle = 90, size = 15, hjust = 1, vjust = 0.5),axis.title.x = element_blank()) +
theme(axis.text.y = element_text(colour = 'black', size = 15, hjust = 0.5, vjust = 0.5), axis.title.y = element_blank()) +
theme(strip.text.x = element_text(size = 14, hjust = 0.5, vjust = 0.5, face = 'bold')) +
facet_wrap(~region, scales="free_y")
Outcome:
Question:
My two variables plotted, yield (%change) and ev (in million US$) have different units. Is there a way to add a secondary y-axis for one of the variable so as to display each variable with a boxplot representing its original units, but within the same plot? Does this feature exist in ggplot2 to begin with?
Thanks!
With ggplot2 you can't make two y axis (see explanation/discussion).
To represent different axis values for ev and yield you have to plot them in separate plots. One way to achieve this would be to use facet_wrap() and combine region and variable values. With facet_wrap() you will get both plots together and you will be able to control number of columns to show.
ggplot(data = distevyield.f, aes(factor(1), value)) +
geom_boxplot() + facet_wrap(region~variable,scales="free",ncol=8)+
theme(axis.text.x=element_blank(),
axis.title.x=element_blank(),
axis.title.y = element_blank())

Resources