Edit the livery of the legend in a geom_area plot - r

How to add livery for the legend in geom_area? I tried something but it does not work.
time<-as.POSIXlt(c("2013-07-01","2013-07-01","2013-07-02","2013-07-02"),origin = "1960-01-01",tz="GMT")
data<-data.frame(xAxis=time,yAxis=c(3,2,1,2),split=factor(c(1,2,1,2)))
p<-ggplot(data,aes(x=xAxis,y=yAxis,fill=split))
p<-p + geom_area(stat="identity")
#p <- p + scale_color_discrete(name ="Name", labels=LETTERS[1:2])
p <- p + xlab("x-Axis") + ylab("y-Axis")
p

I think you need a scale that better matches your aes in ggplot
ggplot(data, aes(x = xAxis, y = yAxis, fill = split)) +
geom_area(stat = "identity") +
scale_fill_discrete(name = "Name", labels = LETTERS[1:2])
If you are going to use 'split' repeatedly and always want to have the same labels, you might consider re-labelling the factor before you start plotting (or whenever informative labels of a factor is relevant, e.g. modelling).
data$split2 <- factor(data$split, labels = LETTERS[1:2])
# no need for the 'labels' argument in scale
ggplot(data, aes(x = xAxis, y = yAxis, fill = split2)) +
geom_area(stat = "identity") +
scale_fill_discrete(name = "Name")

Related

Can I manually change boxplot color with ggMarginal?

I'm using ggMarginal to make marginal boxplots. Is there a way to manually change the color and/or fill of the boxplots without a grouping variable? I'd like to have different colors on the x boxplot and the y boxplot.
library(tidyverse)
library(ggExtra)
foo <- data.frame(x=rnorm(100,mean=1,sd=1),
y=rnorm(100,mean=2,sd=2))
p1 <- ggplot(data = foo,aes(x=x,y=y)) +
geom_point() + coord_equal()
ggMarginal(p1, type="boxplot", size=12)
Provided I have understood you correctly, you can do the following
p1 <- ggplot(data = foo, aes(x = x, y = y)) +
geom_point() +
coord_equal()
ggMarginal(
p1,
type = "boxplot",
size = 12,
xparams = list(colour = "blue"),
yparams = list(colour = "red"))

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

How to start a ggplot with a negative x axis value when data do not contain negative value?

I have some labels in the data that I want to annotate on the plot. I am trying to use directlabels package for annotation. Following is what I get:
library(directlabels)
ggplot(data =appr_CF_nlc %>% filter(SP_AB_Gp==7),
aes(x = frame_index, y = LV_frspacing.m, color = label, group=label)) + geom_line() +
geom_dl(aes(label = label), method = list(dl.trans(x = x+.2), "first.points"))
You can see that labels are not completely visible. How can I fix this? I have tried using scale_x_continuous with no luck:
ggplot(data =appr_CF_nlc %>% filter(SP_AB_Gp==7),
aes(x = frame_index, y = LV_frspacing.m, color = label, group=label)) + geom_line() +
geom_dl(aes(label = label), method = list(dl.trans(x = x + 0.), "first.points")) +
scale_x_continuous(expand=c(0.5,0), limits=c(0, 3500))

facet ordering and then labeling x axis

i have this dataframe and I'd like to use scale_x_discrete to label the x axis
dat = data.frame(group= c("A","B","B"),y = c(1,2,3),row = c(1,1,2),LABEL = c("la","la","lb"))
ggplot(dat, aes(x= row, y = y))+geom_point()+facet_wrap(~group)+
scale_x_discrete(
breaks = row,
labels = LABEL
)
but I get an error: Error in check_breaks_labels(breaks, labels) : object 'LABEL' not found
any idea how to fix it?
Thank you.
If you want x to be discrete, you'll need to make it a factor with x = factor(row).
Then just reference the dat data frame explicitly in scale_x_discrete:
ggplot(dat, aes(x = factor(row), y = y)) +
geom_point() +
facet_wrap(~group) +
scale_x_discrete(breaks = dat$row, labels = dat$LABEL)
Alternately, you can keep x as continuous and use scale_x_continuous instead to relabel the ticks:
ggplot(dat, aes(x = row, y = y)) +
geom_point() +
facet_wrap(~group) +
scale_x_continuous(breaks = dat$row, labels = dat$LABEL)

Dynamically formatting individual axis labels in ggplot2

This may end up being an expression or call question, but I am trying to conditionally format individual axis labels.
In the following example, I'd like to selectively bold one of the axis labels:
library(ggplot2)
data <- data.frame(labs = c("Oranges", "Apples", "Cucumbers"), counts = c(5, 10, 12))
ggplot(data = data) +
geom_bar(aes(x = labs, y = counts), stat="identity")`
There is similar problem here, but the solution involves theme and element_text. I am trying to use axis labels directly.
I can do this manually as below:
breaks <- levels(data$labs)
labels <- breaks
labels[2] <- expression(bold("Cucumbers"))
ggplot(data = data) +
geom_bar(aes(x = labs, y = counts), stat="identity") +
scale_x_discrete(label = labels, breaks = breaks)
But, if I try to do it by indexing instead of typing out "Cucumbers", I get the following error:
breaks <- levels(data$labs)
labels <- breaks
labels[2] <- expression(bold(labels[2]))
ggplot(data = data) +
geom_bar(aes(x = labs, y = counts), stat="identity") +
scale_x_discrete(label = labels, breaks = breaks)
Which makes sense, because it is not evaluating the labels[2]. But, does anyone know how to force it to do that? Thanks.
How about
breaks <- levels(data$labs)
labels <- as.expression(breaks)
labels[[2]] <- bquote(bold(.(labels[[2]])))
ggplot(data = data) +
geom_bar(aes(x = labs, y = counts), stat="identity") +
scale_x_discrete(label = labels, breaks = breaks)
Here we are more explicit about the conversion to expression and we use bquote() to insert the value of the label into the expression itself.
Another option is to set the font face dynamically with theme, though I'm not sure if this is in any sense a better or worse method than #MrFlick's answer:
breaks <- levels(data$labs)
# Reference breaks by name
toBold = "Cucumbers"
ggplot(data = data) +
geom_bar(aes(x = labs, y = counts), stat="identity") +
scale_x_discrete(label = labels, breaks = breaks) +
theme(axis.text.x=
element_text(face=ifelse(breaks %in% toBold, "bold", "plain")))
# Reference breaks by position
label.index=2
ggplot(data = data) +
geom_bar(aes(x = labs, y = counts), stat="identity") +
scale_x_discrete(label = labels, breaks = breaks) +
theme(axis.text.x=
element_text(face=ifelse(breaks %in% labels[match(label.index, 1:length(breaks))],
"bold", "plain")))

Resources