Add multiple geom_line to ggplot - r

The geom_line CUR_MTH_UNEARN_REV_EUR is plotted correctly as a numeric. My goal is to add a second numeric geom_line (i.e., CUR_MTH_EARN_REV_EUR). Here's the code:
library("ggthemes")
library("gridExtra")
library("grid")
p = ggplot(f, aes(DTE_OF_REPORT_EUR, CUR_MTH_UNEARN_REV_EUR, label=(CUR_MTH_UNEARN_REV_EUR)))
+ geom_point(size=ifelse(f$CUR_MTH_UNEARN_REV_EUR<8.0, 11, 5), color=ifelse(f$CUR_MTH_UNEARN_REV_EUR<8.0, '#CC0000', 'black'))
+ geom_line(size=2,aes(group=1)) + geom_rangeframe() + theme_wsj()
+ theme(axis.text.x=element_text(angle=50, size=20, vjust=0.7))
+ geom_smooth(aes(group=1), method="loess", colour = "#CC0000", lwd=2)
+ geom_text(aes(label=CUR_MTH_UNEARN_REV_EUR), hjust=-0.5, vjust=0.5, fontface="bold")
+ ggtitle("Unearned Revenue by Service Code 'BS', in CSG Months, Jul. 2014-Aug. 2015")
+ theme(plot.title = element_text(lineheight=.8, face="bold"))
p
Text1 = textGrob("Source: Revenue Assurance and Quality Control", gp=gpar(fontsize=7))
p2 = p + annotation_custom(grob = Text1, ymin = -0.2, ymax = -30)
p2
format(round(f$CUR_MTH_UNEARN_REV_EUR, 2), nsmall = 2)
f$ScoreRounded <- round(f$CUR_MTH_UNEARN_REV_EUR, 1)
f$DTE_OF_REPORT_EUR <- factor(f$DTE_OF_REPORT_EUR, levels=unique(as.character(f$DTE_OF_REPORT_EUR)))

Hope this helps as a start. You can just add things, but you need to have the correct aes.
#data with x and two y-variables
set.seed(123)
f <- data.frame(x=1:10, var1=sample(7:10,10,T),
var2=sample(5:7,10,T))
#as you want sizing by a measure, make a flag
f$var1_threshold <- f$var1 <9
#example with adding different geoms
#not that it's unnecessary to use my data (f)
#in the call to aes, as everything I need is already
#inside f
p <- ggplot(f, aes(x=x)) +
geom_point(aes(y=var1,size=var1_threshold, color=var1_threshold))+
#colors and size in aes allows for legend generation.
scale_size_manual(values=c("FALSE"=5,"TRUE"=8)) +
scale_color_manual(values=c("FALSE"='#CC0000',"TRUE"='black')) +
geom_line(aes(y=var1),size=1) +
geom_line(aes(y=var2),size=1) +
geom_smooth(aes(y=var1), colour="#CC0000") +
geom_smooth(aes(y=var2), colour="black")

Related

multiple axis in a ggplot [duplicate]

Is there a possibility to add a third y-axis to a plot with ggplot2?
I have three different datasources I want to display in the plot. I already added a second y-axis, for the next dataset the scale is again very different, why I'm looking now for a solution.
So far I only found how to add a second axis, for example as shown [here].(https://r-graph-gallery.com/line-chart-dual-Y-axis-ggplot2.html)
But I whether there is an possibility to add another one... Thank you!
This is equally clunky, but shows how it can be done from scratch using only CRAN resources.
library(cowplot)
library(patchwork)
p1 <- ggplot(df, aes(Sepal.Width, Sepal.Length)) +
geom_point() + theme(axis.line = element_line())
p2 <- ggplot(df, aes(Sepal.Width, Petal.Width)) + geom_point() +
theme(axis.line = element_line())
p3 <- ggplot(df, aes(Sepal.Width, Petal.Length)) +
geom_point(aes(color = "Petal.Length")) +
geom_point(aes(y = Sepal.Length/100, color = "Sepal.Length")) +
geom_point(aes(y = Petal.Width / 1000, color = "Petal.Width")) +
theme(axis.line = element_line(),
plot.margin = margin(10, 10, 10, 30))
wrap_elements(get_plot_component(p1, "ylab-l")) +
wrap_elements(get_y_axis(p1)) +
wrap_elements(get_plot_component(p2, "ylab-l")) +
wrap_elements(get_y_axis(p2)) +
p3 +
plot_layout(widths = c(3, 1, 3, 1, 40))
Data used
df <- iris
df$Sepal.Length <- df$Sepal.Length * 100
df$Petal.Width <- df$Petal.Width * 1000
This is a very clunky solution based on extracting elements from previously plotted graphs and editing grid objects. It may or not give you a workable solution.
source("https://raw.githubusercontent.com/davidearn/plague_growth/master/analysis/plots/3axes.R")
set.seed(101)
dd <- data.frame(x=rnorm(20),y=rnorm(20))
library(ggplot2)
gg0 <- ggplot(dd)
g1A <- gg0 + geom_point(aes(x,y))
g1B <- gg0 + geom_point(aes(x,10*y))
g1C <- gg0 + geom_point(aes(x,100*y))
## use return_gtable = TRUE if planning to add further axes
g2 <- combine_axes(g1A,g1B,add_pos="l", return_gtable=TRUE)
g3 <- combine_axes(g2,g1C,add_pos="l")
print(g3)

Is it possible to add a third y-axis to ggplot2?

Is there a possibility to add a third y-axis to a plot with ggplot2?
I have three different datasources I want to display in the plot. I already added a second y-axis, for the next dataset the scale is again very different, why I'm looking now for a solution.
So far I only found how to add a second axis, for example as shown [here].(https://r-graph-gallery.com/line-chart-dual-Y-axis-ggplot2.html)
But I whether there is an possibility to add another one... Thank you!
This is equally clunky, but shows how it can be done from scratch using only CRAN resources.
library(cowplot)
library(patchwork)
p1 <- ggplot(df, aes(Sepal.Width, Sepal.Length)) +
geom_point() + theme(axis.line = element_line())
p2 <- ggplot(df, aes(Sepal.Width, Petal.Width)) + geom_point() +
theme(axis.line = element_line())
p3 <- ggplot(df, aes(Sepal.Width, Petal.Length)) +
geom_point(aes(color = "Petal.Length")) +
geom_point(aes(y = Sepal.Length/100, color = "Sepal.Length")) +
geom_point(aes(y = Petal.Width / 1000, color = "Petal.Width")) +
theme(axis.line = element_line(),
plot.margin = margin(10, 10, 10, 30))
wrap_elements(get_plot_component(p1, "ylab-l")) +
wrap_elements(get_y_axis(p1)) +
wrap_elements(get_plot_component(p2, "ylab-l")) +
wrap_elements(get_y_axis(p2)) +
p3 +
plot_layout(widths = c(3, 1, 3, 1, 40))
Data used
df <- iris
df$Sepal.Length <- df$Sepal.Length * 100
df$Petal.Width <- df$Petal.Width * 1000
This is a very clunky solution based on extracting elements from previously plotted graphs and editing grid objects. It may or not give you a workable solution.
source("https://raw.githubusercontent.com/davidearn/plague_growth/master/analysis/plots/3axes.R")
set.seed(101)
dd <- data.frame(x=rnorm(20),y=rnorm(20))
library(ggplot2)
gg0 <- ggplot(dd)
g1A <- gg0 + geom_point(aes(x,y))
g1B <- gg0 + geom_point(aes(x,10*y))
g1C <- gg0 + geom_point(aes(x,100*y))
## use return_gtable = TRUE if planning to add further axes
g2 <- combine_axes(g1A,g1B,add_pos="l", return_gtable=TRUE)
g3 <- combine_axes(g2,g1C,add_pos="l")
print(g3)

Bunched up x axis ticks on multi panelled plot in ggplot

I am attempting to make a multi-panelled plot from three individual plots (see images).However, I am unable to rectify the bunched x-axis tick labels when the plots are in the multi-panel format. Following is the script for the individual plots and the multi-panel:
Individual Plot:
NewDat [[60]]
EstRes <- NewDat [[60]]
EstResPlt = ggplot(EstRes,aes(Distance3, `newBa`))+geom_line() + scale_x_continuous(n.breaks = 10, limits = c(0, 3500))+ scale_y_continuous(n.breaks = 10, limits = c(0,25))+ xlab("Distance from Core (μm)") + ylab("Ba:Ca concentration(μmol:mol)") + geom_hline(yintercept=2.25, linetype="dashed", color = "red")+ geom_vline(xintercept = 1193.9, linetype="dashed", color = "grey")+ geom_vline(xintercept = 1965.5, linetype="dashed", color = "grey") + geom_vline(xintercept = 2616.9, linetype="dashed", color = "grey") + geom_vline(xintercept = 3202.8, linetype="dashed", color = "grey")+ geom_vline(xintercept = 3698.9, linetype="dashed", color = "grey")
EstResPlt
Multi-panel plot:
MultiP <- grid.arrange(MigrPlt,OcResPlt,EstResPlt, nrow =1)
I have attempted to include:
MultiP <- grid.arrange(MigrPlt,OcResPlt,EstResPlt, nrow =1)+
theme(axis.text.x = element_text (angle = 45)) )
MultiP
but have only received errors. It's not necessary for all tick marks to be included. An initial, mid and end value is sufficient and therefore they would not need to all be included or angled. I'm just not sure how to do this. Assistance would be much appreciated.
There are several options to resolve the crowded axes. Let's consider the following example which parallels your case. The default labelling strategy wouldn't overcrowd the x-axis.
library(ggplot2)
library(patchwork)
library(scales)
df <- data.frame(
x = seq(0, 3200, by = 20),
y = cumsum(rnorm(161))
)
p <- ggplot(df, aes(x, y)) +
geom_line()
(p + p + p) / p &
scale_x_continuous(
name = "Distance (um)"
)
However, because you've given n.breaks = 10 to the scale, it becomes crowded. So a simple solution would just be to remove that.
(p + p + p) / p &
scale_x_continuous(
n.breaks = 10,
name = "Distance (um)"
)
Alternatively, you could convert the micrometers to millimeters, which makes the labels less wide.
(p + p + p) / p &
scale_x_continuous(
n.breaks = 10,
labels = label_number(scale = 1e-3, accuracy = 0.1),
name = "Distance (mm)"
)
Yet another alternative is to put breaks only every n units, in the case below, a 1000. This happens to coincide with omitting n.breaks = 10 by chance.
(p + p + p) / p &
scale_x_continuous(
breaks = breaks_width(1000),
name = "Distance (um)"
)
Created on 2021-11-02 by the reprex package (v2.0.1)
I thought it would be better to show with an example.
What I mean was, you made MigrPlt, OcResPlt, EstResPlt each with ggplot() +...... For plot that you want to rotate x axis, add + theme(axis.text.x = element_text (angle = 45)).
For example, in iris data, only rotate x axis text for a like
a <- ggplot(iris, aes(Sepal.Width, Sepal.Length)) +
geom_point() +
theme(axis.text.x = element_text (angle = 45))
b <- ggplot(iris, aes(Petal.Width, Petal.Length)) +
geom_point()
gridExtra::grid.arrange(a,b, nrow = 1)

How to fit a lot of x labels or space out x labels in ggplot2

Is there a way to space out so that each x label is more distinguishable?
I feel like this question has been asked before but I can't seem to find an answer. I believe the graph needs to be bigger for this to work, is their a way to make the graph bigger within Rstudio? or make the text smaller
My code so far :
bar_plt = ggplot(data, aes(fct_infreq(Event))) + geom_bar(fill = "dodgerblue", width = .4) +
xlab("Event Names") + ylab("Number of Observations") + coord_flip()
TIA
what about working with labels in this way (sorry for the fake data, but I have not got a sample of your):
library(ggplot2)
# numbers
set.seed(1)
y<-sample(1:30, 500, TRUE)
# very long and numerous labels
x <- paste(sample(letters[1:22], 500, TRUE),sample(letters[1:2], 500, TRUE),'abcdefghijklmnopqrstuvwxyz')
data <- data.frame(x,y)
# simple ggplot barplot
p <- ggplot(data, aes(x = x, y = y)) + geom_bar(stat = "identity") + coord_flip()
# play with the size to have a fitting dimension
p <- p + theme(axis.text.y = element_text(face="bold", color="black", size=8))
# you can also abbreviate the labels if necessary
p <- p + scale_x_discrete(labels = abbreviate)
p
Your plot could be something like:
library(forcats)
library(ggplot2)
# data
set.seed(1)
Events <- paste(sample(letters[1:22], 500, TRUE),sample(letters[1:2], 500, TRUE),'abcdefghijklmnopqrstuvwxyz')
data <- data.frame(Events)
bar_plt <- ggplot(data, aes(fct_infreq(Events))) + geom_bar(fill = "dodgerblue", width = .4) + coord_flip()
bar_plt <- bar_plt + xlab("Event Names") + ylab("Number of Observations")
bar_plt <- bar_plt + theme(axis.text.y = element_text(face="bold", color="black", size=8))
bar_plt <- bar_plt + scale_x_discrete(labels = abbreviate)
bar_plt

manual color assignment of a legend object in ggplot2

This is my code:
library(data.table)
library(ggplot2)
clist <- list(c(1:39), c(2:40), c(3:41))
clist.ts <- lapply(clist, function(x) ts(x, frequency = 1, start = 1978))
ind78_ymean_tsdf <- as.data.frame(clist.ts)
names(ind78_ymean_tsdf) <- c("name1", "name2", "name3")
ind78_ymean_tsdf$"Year" <- c(1978:2016)
setDT(ind78_ymean_tsdf)
ind78_ymean_melt <- melt(ind78_ymean_tsdf, id=c("Year"))
(ggplot(ind78_ymean_melt, aes(x=Year, y=value, color=variable))
+ geom_line()
+ geom_line(data=subset(ind78_ymean_melt, variable == "name1"), colour="black", size=1.5)
+ labs(title="Development of the indices", x="Year", y="Index")
+ scale_color_discrete(name="Individual replications")
+ theme_light())
# + guides(colour=guide_legend(override.aes=list(colour=c(hue_pal()(11)[1:10], "black"), size=c(rep(1, 10), 1.5))))
It is basically the same as in the following question, but with a reproducible example: manual color assignment
My problem is now, that I don't know how I had to change the following line in order to get the entry in the legend of the plot also black:
guides(colour=guide_legend(override.aes=list( colour=c(hue_pal()(11)[1:10], "black"), size=c(rep(1, 10), 1.5))))
Maybe someone could explain what the parameters in the line above mean or could post the question to the link above, because I have not enough street cred. to do so.. :) I have 13 variables in the real plot (not in the reproducible example above) if that helps. Thanks in advance!
Your solution looks overcomplicated. Why don't you simply scale_color_manual and scale_size_manual.
ggplot(ind78_ymean_melt, aes(Year, value, color = variable, size = variable)) +
geom_line() +
labs(title = "Development of the indices",
x = "Year",
y = "Index",
color = "Individual replications") +
scale_color_manual(values = c("black", hue_pal()(2))) +
scale_size_manual(values = c(1.5, rep(0.5, 2))) +
theme_light() +
guides(size = FALSE)
This is the solution from #drmariod:
(ggplot(ind78_ymean_melt, aes(x=Year, y=value, color=variable), size=2)
+ geom_line()
+ geom_line(data=subset(ind78_ymean_melt, variable == "name3"), colour="black", size=1.5)
+ labs(title="Development of the indices", x="Year", y="Index")
+ scale_color_discrete(name="Individual replications")
+ theme_light()
+ guides(colour=guide_legend(override.aes=list( colour=c(hue_pal()(2), "black"), size=c(rep(1, 2), 1.0)))) )
And the explanation of the last code line: the hue_pal()(11) creates 11 colours from the hue palette but it chooses only color 1:10 and adds a black color to it.

Resources