ggplot legend not showing up in lift chart - r

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

Related

How to segregate by one factor but colour by another in ggplot2 R?

In my dataset, I have segregated the data by a parameter par for either Black or Red noise that are staggered in represtation. Now, for both species, I want to colour the "Black" noise as black, and "Red" as red. Furthermore, I want to join the points by par -- specifically, I want to join par -- No with a Dashed line, and Yes as a solid line. I tried the piece of code attached (and multiple versions of it)..but no luck. Any suggestions?
#Data
set.seed(100)
sp <- factor(c("A","A","A","A","B","B","B","B"))
par <- factor(c("No","No","Yes","Yes","No","No","Yes","Yes"))
y <- rnorm(8, 2,3)
noise <- factor(c("Black","Red","Black","Red","Black","Red","Black","Red"))
df <- data.frame(sp, par, y, noise)
df$noise <- factor(df$noise, levels = c("Black","Red"))
library(ggplot2)
ggplot(data = df, aes(x = noise, y = y, fill = par, color = par)) +
geom_point(size = 4) +
facet_wrap(.~sp) +
theme_classic() +
scale_fill_manual(values = c("black","red")) + scale_color_manual(values = c("black","red")) +
geom_line(aes(linetype=par)) + scale_linetype_manual(name = "indicator", values = c(2,1,2))
geom_path(aes(group = par,linetype=par), geom = "path")
ERROR: geom_path: Each group consists of only one observation. Do you need to adjust the group aesthetic?
In your code, you forget to add a + to link geom_path() with the ggplot(). Since the aes() of geom_point() and geom_path() doesn't match, you'll need to include them in the corresponding geom_*().
library(tidyverse)
ggplot(data = df, aes(x = noise, y = y, group = par, linetype = par)) +
geom_point(aes(fill = noise, color = noise, ), size = 4) +
facet_wrap(.~sp) +
theme_classic() +
scale_fill_manual(values = c("black","red")) +
scale_color_manual(values = c("black","red")) +
geom_line() +
scale_linetype_manual(name = "indicator", values = c(2,1,2)) +
geom_path()

adding a label in geom_line in R

I have two very similar plots, which have two y-axis - a bar plot and a line plot:
code:
sec_plot <- ggplot(data, aes_string (x = year, group = 1)) +
geom_col(aes_string(y = frequency), fill = "orange", alpha = 0.5) +
geom_line(aes(y = severity))
However, there are no labels. I want to get a label for the barplot as well as a label for the line plot, something like:
How can I add the labels to the plot, if there is only pone single group? is there a way to specify this manually? Until know I have only found option where the labels can be added by specifying them in the aes
EXTENSION (added a posterior):
getSecPlot <- function(data, xvar, yvar, yvarsec, groupvar){
if ("agegroup" %in% xvar) xvar <- get("agegroup")
# data <- data[, startYear:= as.numeric(startYear)]
data <- data[!claims == 0][, ':=' (scaled = get(yvarsec) * max(get(yvar))/max(get(yvarsec)),
param = max(get(yvar))/max(get(yvarsec)))]
param <- data[1, param] # important, otherwise not found in ggplot
sec_plot <- ggplot(data, aes_string (x = xvar, group = groupvar)) +
geom_col(aes_string(y = yvar, fill = groupvar, alpha = 0.5), position = "dodge") +
geom_line(aes(y = scaled, color = gender)) +
scale_y_continuous(sec.axis = sec_axis(~./(param), name = paste0("average ", yvarsec),labels = function(x) format(x, big.mark = " ", scientific = FALSE))) +
labs(y = paste0("total ", yvar)) +
scale_alpha(guide = 'none') +
theme_pubclean() +
theme(legend.title=element_blank(), legend.background = element_rect(fill = "white"))
}
plot.ExposureYearly <- getSecPlot(freqSevDataAge, xvar = "agegroup", yvar = "exposure", yvarsec = "frequency", groupvar = "gender")
plot.ExposureYearly
How can the same be done on a plot where both the line plot as well as the bar plot are separated by gender?
Here is a possible solution. The method I used was to move the color and fill inside the aes and then use scale_*_identity to create and format the legends.
Also, I needed to add a scaling factor for severity axis since ggplot does not handle the secondary axis well.
data<-data.frame(year= 2000:2005, frequency=3:8, severity=as.integer(runif(6, 4000, 8000)))
library(ggplot2)
library(scales)
sec_plot <- ggplot(data, aes(x = year)) +
geom_col(aes(y = frequency, fill = "orange"), alpha = 0.6) +
geom_line(aes(y = severity/1000, color = "black")) +
scale_fill_identity(guide = "legend", label="Claim frequency (Number of paid claims per 100 Insured exposure)", name=NULL) +
scale_color_identity(guide = "legend", label="Claim Severity (Average insurance payment per claim)", name=NULL) +
theme(legend.position = "bottom") +
scale_y_continuous(sec.axis =sec_axis( ~ . *1, labels = label_dollar(scale=1000), name="Severity") ) + #formats the 2nd axis
guides(fill = guide_legend(order = 1), color = guide_legend(order = 2)) #control which scale plots first
sec_plot

Additional legend in ggplot2

I have a problem where the legend of my ggplot() does not appear. Here's my code:
plot_bt <- ggplot(NULL, aes(x, v1)) +
geom_line(data = nig_bt_1, colour = "black") +
geom_line(data = nig_bt_2, colour = "blue") +
geom_line(data = nig_bt_3, colour = "red") +
labs(x = "X", y = "Probability")
I tried to make a legend inside this graph but I could not do it. It just does not appear. I try to make a plot of three different types of NIG distribution. In nig_bt_1 etc. I have my values. Those three densities appear but the legend doesn't. I tried the scale_color_manual function too with no success.
Thank you very much.
x <- seq(-7.5,7.5,0.001)
nig_bt_1 <- data.frame(x ,v1 = dnig(x, param = pr_bt_1))
nig_bt_2 <- data.frame(x ,v1 = dnig(x, param = pr_bt_2))
nig_bt_3 <- data.frame(x ,v1 = dnig(x, param = pr_bt_3))
Just do this:
plot_bt <- ggplot(NULL, aes(x, v1)) +
geom_line(data = nig_bt_1, aes(colour = "a")) +
geom_line(data = nig_bt_2, aes(colour = "b")) +
geom_line(data = nig_bt_3, aes(colour = "c")) +
labs(x = "X", y = "Probability") +
scales_color_manual(values= c("a" = "black", "b" = "blue", "c" = "red"))
A guide can only depict mappings you've defined using aes. The ggplot2 way is of course to first combine the data and use a grouping variable.

Have separate legends for a set of point-line plots, and a vertical line plot

Example data frame (if there's a better/more idiomatic way to do this, let me know):
n <- 10
group <- rep(c("A","B","C"),each = n)
x <- rep(seq(0,1,length = n),3)
y <- ifelse(group == "A",1+x,ifelse(group == "B",2+2*x,3+3*x))
df <- data.frame(group,x,y)
xd <- 0.5
des <- data.frame(xd)
I want to plot create point-line plots for the data in df, add a vertical curve at the x location indicated by xd, and get readable legends for both. I tried the following:
p <- ggplot(data = df, aes(x = x, y = y, color = group)) + geom_point() + geom_line(aes(linetype=group))
p <- p + geom_vline(data = des, aes(xintercept = xd), color = "blue")
p
Not quite what I had in mind, there's no legend for the vertical line.
A small modification (I don't understand why geom_vline is one of the few geometries with a show.legend parameter, which moreover defaults to FALSE!):
p <- ggplot(data = df, aes(x = x, y = y, color = group)) + geom_point() + geom_line(aes(linetype=group))
p <- p + geom_vline(data = des, aes(xintercept = xd), color = "blue", show.legend = TRUE)
p
At least now the vertical bar is showing in the legend, but I don't want it to go in the same "category" (?) as group. I would like another legend entry, titled Design, and containing only the vertical line. How can I achieve this?
A possible approach is to add an extra dummy aesthetic like fill =, which we'll subsequently use to create the second legend in combination with scale_fill_manual() :
ggplot(data = df, aes(x = x, y = y, color = group)) +
geom_point() +
geom_line(aes(linetype=group), show.legend = TRUE) +
geom_vline(data = des,
aes(xintercept = xd, fill = "Vertical Line"), # add dummy fill
colour = "blue") +
scale_fill_manual(values = 1, "Design", # customize second legend
guide = guide_legend(override.aes = list(colour = c("blue"))))

How to add colour and legend in multiple line plot on ggplot without using melt from reshape package?

I am plotting two lines on same plot with sme x axis by following lines.
i am implementing the lower line but unable to see colors and legend
ggplot(final, aes(x = Date)) + geom_line(aes(y = cocastock)) + geom_line(aes(y = procterstock)) + scale_color_manual(values = c(cocastock = '#008B00', procterstock = '#FFFFFF'))
also tried
ggplot(final, aes(x = Date)) + geom_line(aes(y = cocastock)) + geom_line(aes(y = procterstock)) + scale_color_manual(values = c('#008B00','#FFFFFF'))
but dosen't work
scale_colour_manual only works when you have specified colour in aes, hence you need:
ggplot(final, aes(x = Date)) +
geom_line(aes(y = cocastock, colour = "cocastock")) +
geom_line(aes(y = procterstock, colour = "procterstock")) +
scale_color_manual(values = c(cocastock = '#008B00', procterstock = '#FFFFFF'))

Resources