How do I add legends when there are two y variables? - r

This is the code I used:
ggplot(Delays2006, aes(Month)) + geom_point(aes(y = delay), color = "blue", size = 2)
+ geom_point(aes(y=delay2)) + scale_x_discrete(limits=(month.name))
+ labs(x= "Months", y = "Delays in minutes") + ggtitle(" Flight Data 2006")
This is the output:
May I ask how do I add legends to delay and delay2 in this graph. Thank you.

If you want to have a legend you have to map on aesthetics, i.e. do geom_point(aes(y = delay, color = "delay")) + geom_point(aes(y=delay2, color = "delay2")). Colors and labels could then be set via scale_color_manual.
Using mtcars as example data:
library(ggplot2)
ggplot(mtcars, aes(mpg)) +
geom_point(aes(y = hp, color = "hp")) +
geom_point(aes(y = cyl, color = "cyl")) +
scale_color_manual(values = c(hp = "blue", cyl = "green"), labels = c(hp = "Horse Power", cyl = "Cylinders"))

Related

How to add individual labels to points on a line graph in R

I am wanting to add labels pointing out the year of the 3 highest, and 3 lowest temperatures on a line graph showing changes in average temperature. I can't figure out how to do so for just those 6 points, instead of every point... Any help?
#load data up
library(readxl)
TempData <- read_excel("R Data/TempData.xlsx")
View(TempData)
#initiliase relevant packages #ggplot2 for creating data visulation and viridis to allow for colour gradients
library(ggplot2)
library(viridis)
#plot line graph
g1 <- ggplot(TempData, aes(x = Year, y = GAT, color = GAT)) +
geom_line(size = 1.5) +
geom_smooth(method=loess, se=TRUE, col = "black") +
scale_colour_gradient2(low = "green", mid = "yellow" , high = "red", midpoint=median(TempData$GAT)) +
labs(title = "Global Average Temperature", subtitle = "From 1850 to 2018") +
xlab("Year") + ylab ("Average Temperature") +
theme(plot.title = element_text(face = "bold", hjust = 0.5, size = 16)) +
theme(plot.subtitle = element_text(face = "italic", hjust = 0.5, size = 10, colour = "Orange")) +
theme_light()
plot(g1)
As #Nate suggested, a common approach is to feed a subset of your data into geom_text. You could define those before ggplot2 or if it's simple, define those inline and feed into that layer's own data term. Here, I use dplyr::top_n to grab the top 3 and bottom 3 weights.
library(dplyr)
ggplot(mtcars, aes(x = wt, y = mpg, color = hp, label = mpg)) +
geom_line(size = 1.5) +
geom_smooth(method=loess, se=TRUE, col = "black") +
scale_colour_gradient2(low = "green", mid = "yellow" , high = "red",
midpoint=median(mtcars$hp)) +
geom_text(data = mtcars %>% top_n(3, wt),
hjust = 1.5, color = "black", angle = 90) +
geom_text(data = mtcars %>% top_n(-3, wt),
hjust = -0.5, color = "black", angle = 90) +
theme_light()
We don't have your data so I took your code and applied it to the standard mtcars dataset. (Not a great aesthetic match but you get the idea...)

adding colors to geom_point() in ggplot2 with a box plot overlay

I want to change the colors of the points to reflect the "fluorophore" column in my data (either red, green, or amber). However, whenever I do this manually using scale_color_manual, it changes the boxplot to be each individual fluorophore color as well. I want the boxplot to be for each well number, but the data points to be colored according to fluorophore!
ggplot(sample1_50kreg, aes(x = well_number, y = cq)) +
geom_boxplot() +
geom_point(color = "purple", alpha = 0.5) +
theme_bw()
[]
ggplot(sample1_50kreg, aes(x = well_number, y = cq, color=fluorophore)) +
geom_point(alpha = 0.5) +
geom_boxplot () +
theme_bw() +
scale_color_manual(breaks = c("red", "green", "amber"),
values = c("gold", "green", "red"))
[]
sample1_50kreg <- as.factor(sample1_50kreg$fluorophore)
and re-run your script
check: http://www.sthda.com/english/wiki/ggplot2-colors-how-to-change-colors-automatically-and-manually
I figured it out!
ggplot(sample1_50kreg, aes(x = well_number, y = cq)) +
geom_boxplot() +
theme_bw() +
geom_point (aes(color = fluorophore)) +
scale_color_manual(breaks = c("red", "green", "amber"),
values = c("gold", "green", "red"))

How to use ggplot2 legend to denote different geoms

I am using ggplot2 to plot points from a .csv file that is just a column used a x values and a column used a y values. I am a little confused as to how ggplot decides what to make a legend for and haven't found any good examples online.
I would like the legend to show that geom_point is stress vs strain, and my geom_smooth is the best fit line.
Here is my code:
library(ggplot2)
imported = read.csv("data.csv")
Strain = imported$Strain
Stress = imported$Stress..N.m.2.
err = .0005
gg <-
ggplot(imported, aes(x=Strain, y=Stress)) +
geom_point(aes(group = "Points"), shape = 79, colour = "black", size = 2, stroke = 4) +
geom_smooth(method = "lm", se = FALSE, color = "orange") +
geom_errorbarh(xmin = Strain - err, xmax = Strain + err, show.legend = TRUE) +
theme_gray() + ggtitle("Stress vs Strain") +
theme(legend.position = "top")
gg
And it is producing the following plot:
my plot
Edit: added approach at top to create legend for each geom, by creating dummy mapping to separate aesthetics.
library(ggplot2)
ggplot(mtcars, aes(mpg, wt)) +
geom_point(aes(color = "point")) + # dummy mapping to color
geom_smooth(method = "lm", se = FALSE, color = "orange",
aes(linetype = "best fit")) + # dummy mapping to linetype
geom_errorbarh(aes(xmin = mpg - 2, xmax = mpg + 1)) +
scale_color_manual(name = "Stress vs. Strain", values = "black") +
scale_linetype_manual(name = "Best fit line", values = "solid")
original answer:
Note the difference in legend here:
library(ggplot2)
ggplot(mtcars, aes(mpg, wt, color = as.character(cyl))) +
geom_point() +
geom_errorbarh(aes(xmin = mpg - 2, xmax = mpg + 1),
show.legend = TRUE) # error bars reflected in legend
ggplot(mtcars, aes(mpg, wt, color = as.character(cyl))) +
geom_point() +
geom_errorbarh(aes(xmin = mpg - 2, xmax = mpg + 1),
show.legend = FALSE) # error bars not shown in legend

ggplot single-value factor remove slashes from legend

I would like to show a simple geom_point, geom_smooth, and geom_abline with helpful legends. Unfortunately, the simple combination of geom_point and geom_smooth places a horizontal line across the point legend, adding geom_abline places a diagonal slash across all legends.
How can I create a simple visual where legend boxes include only a "point", a "line", and a "dashed line"?
Thanks
Examples:
Geom_point and geom_smooth
mtcars %>%
ggplot() +
geom_point(aes(x = carb, y = mpg, color = "Points")) +
geom_smooth(aes(x = carb, y = mpg, color = "Trendline")) +
theme(legend.position="bottom") +
labs(x = "carb",
y = "mpg",
color = "LEGEND")
Geom_point, geom_smooth, and geom_abline
mtcars %>%
ggplot() +
geom_point(aes(x = carb, y = mpg, color = "Points")) +
geom_smooth(aes(x = carb, y = mpg, color = "Trendline")) +
geom_abline(aes(slope = 1, intercept = 10, color = "ZCustom"), linetype = "dashed") +
theme(legend.position="bottom") +
labs(x = "carb",
y = "mpg",
color = "LEGEND")
Fixed geom_point legend, but slashes remain on other legends
mtcars %>%
ggplot() +
geom_point(aes(x = carb, y = mpg, color = "Points")) +
geom_smooth(aes(x = carb, y = mpg, color = "Trendline")) +
geom_abline(aes(slope = 1, intercept = 10, color = "ZCustom"), linetype = "dashed") +
scale_color_manual(values = c("red", "blue", "black"),
label = c("Points", "Trendline", "Custom"),
guide = guide_legend(override.aes = list(
linetype = c("blank", "solid", "dashed"),
shape = c(16, NA, NA)))) +
theme(legend.position="bottom") +
labs(x = "carb",
y = "mpg",
color = "LEGEND")
I have looked at these questions but did not understand how to apply to my situation:
ggplot legend slashes
ggplot2 legend for abline and stat_smooth
Include manually-added lines to ggplot2 guide legend
To me, the easiest way to get around this is to simply not list everything as color. You can use size, shape, alpha, etc. to break up the legend.
mtcars %>%
ggplot() +
geom_point(aes(x = carb, y = mpg, shape = "")) +
geom_smooth(aes(x = carb, y = mpg, alpha = "")) +
geom_abline(aes(slope = 1, intercept = 10, color = ""), linetype = "dashed") +
theme(legend.position="bottom") +
labs(x = "carb",
y = "mpg",
shape = "Points",
alpha = "Trendline",
color = "ZCustom")
My guess: you are using color for both geom_point and geom_smooth, so the legend attempts to combine both geoms.
When you use a different aes, the legend takes them as separate attribute/layers.
mtcars %>%
ggplot( aes(x = carb, y = mpg) ) +
geom_point( aes(fill = "Points") ) + # use 'fill' rather than 'color'
geom_smooth( aes(color = "Trendline") ) +
theme(legend.position = "bottom") +
labs(x = "carb", y = "mpg", color = "", fill = "")
Hope it helps!

ggplot legend not showing up in lift chart

I'm trying to get a legend to show up in a left chart I've developed. It's not showing up. I've checked ggplot legend not working with scale_colour_manual as well as How to add a legend in ggplot (not showing up) to no avail.
Here is some sample data:
#x axis values
deciles <- c(1:10)
#model_1
decile_act_pp <- c(393.6773, 243.0795, 250.2033, 220.0076, 180.7292,
187.3803,208.8504,162.9708,140.9405,107.7656)
#model_2
model2_pp_norm <- c(537.9617, 306.0807, 244.6228, 207.8051, 181.8801,
161.3744,142.8224,125.3262,107.5905, 80.13438)
#model_3
model1_pp_norm <- c(515.9927,297.8425, 240.8723, 206.6129, 183.6805,
164.3337, 148.4509,134.1227, 115.0055, 88.68549)
#combine to make a chart
df <- as.data.frame(cbind(deciles, decile_act_pp, model2_pp_norm,
model1_pp_norm))
#develop the chart
ggplot(data = df, aes(x = as.factor(deciles), group = 1)) +
geom_point(aes(y = decile_act_pp), color = "blue") +
geom_line(aes(y = decile_act_pp), color = "blue") +
geom_point(aes(y = model2_pp_norm), color = "red") +
geom_line(aes(y = model2_pp_norm), color = "red") +
geom_point(aes(y = model1_pp_norm), color = "green") +
geom_line(aes(y = model1_pp_norm), color = "green") +
xlab("Deciles") +
labs(colour="Datasets",x="Deciles",y="Pure Premium") +
scale_color_manual('', limits = c('decile_act_pp', 'model2_pp_norm',
'model1_pp_norm'), values = c("blue", "red", "green"))
The chart look exactly as I want it minus missing the legend. Can anyone tell me what I'm doing wrong?
library(reshape2)
df2 <- melt(data = df, id.vars = 1)
ggplot(data = df2, aes(x = as.factor(deciles), group = 1)) + geom_point(aes( y=value, color = variable)) + geom_line(aes(y = value, group = variable, color = variable))

Resources