Combine two plots in ggplot? - r

I need to create a ggplot that is a column plot overlayed with a line plot. The line plot shows mean values, while the column plot shows how the mean values relate to benchmark values. I've managed to create two separate plots in ggplot, but I'm having trouble combining them.
My line plot looks like this:
And is created using this code:
benchMarkLine <- ggplot(UEQScores, aes(x=Scale, y=Score, group=1)) +
geom_line(size = 1.4, colour = "black") +
geom_point(size = 2.4, colour = "black") +
scale_y_continuous(name = "Score", breaks = seq(0, 2.5, 0.25), limits = c(0, 2.5)) +
scale_x_discrete(name = "Scale") +
ggtitle("Mean Scores") +
theme_bw() + # Set black and white theme +
theme(plot.title = element_text(hjust = 0.5, size=10), # Centre plot title
panel.grid.major = element_blank(), # Turn off major gridlines
panel.grid.minor = element_blank(), # Turn off minor gridlines
axis.title.x = element_text(size=10),
axis.text.x = element_text(angle=30, vjust=0.6),
axis.title.y = element_text(size=10))
benchMarkLine
My Column plot looks like this:
And was created with the following code:
benchmarkColPlot <- ggplot(benchmark_long, aes(x=factor(Scale, scaleLevels), y=value, fill=factor(cat, bmLevels))) +
geom_col(position="fill") +
scale_fill_manual(values = bmColours) +
scale_y_continuous(name = "Score", breaks = seq(-1.0, 1.0, 0.25), limits = c(-1, 1)) +
scale_x_discrete(name = "Scale") +
ggtitle("Benchmark Scores") +
theme_bw() + # Set black and white theme +
theme(plot.title = element_text(hjust = 0.5, size=10), # Centre plot title
panel.grid.major = element_blank(), # Turn off major gridlines
panel.grid.minor = element_blank(), # Turn off minor gridlines
axis.title.x = element_text(size=10),
axis.text.x = element_text(angle=30, vjust=0.6),
axis.title.y = element_text(size=10),
legend.title = element_blank())
benchmarkColPlot
How can I combine these two? I tried inserting geom_line(UEQScores, aes(x=Scale, y=Score, group=1)) + above geom_col(position="fill") + in the column plot code, but I just get the following error:
Error: `mapping` must be created by `aes()`
How do I combine these two plots?
OK, I've given up on this - I just created the chart in Excel as it seems to be a bit easier for what I'm doing here.

Related

How to make faceted pie charts for a dataframe of percentages in R?

I have reached to create a melted dataframe containing as values the % of the energy sources (factor variable) for several Years, as additional factor or Date:
How could I make nice faceted pie charts for the different years with ggplot (or plotrix)?
So, far, I have reached to:
ggplot(melted_df, aes(x=Year, y=Share, fill=Source)) +
geom_bar(stat="identity", width=1)+
coord_polar("y", start=0) +
geom_text(aes(label = paste0(round(Share*100), "%")), position = position_stack(vjust = 0.5),size=3)+
labs(x = NULL, y = NULL, fill = NULL, title = "Energy Mix")+
theme_classic() + theme(axis.line = element_blank(),
axis.text = element_blank(),
axis.ticks = element_blank(),
plot.title = element_text(hjust = 0.5, color = "#666666"))
which without the facet command gives this, which is not aesthetically pleasant:
while if I add the facet_wrap(~Year) command, it becomes worse...
After commentators suggestion, aes(x=1) in the ggplot() line solves the issue and makes normal circle parallel pies:
ggplot(melted_df, aes(x=1, y=Share, fill=Source)) +
geom_col(width=1,position="fill", color = "black")+
coord_polar("y", start=0) +
geom_text(aes(x = 1.7, label = paste0(round(Share*100), "%")), size=2,
position = position_stack(vjust = 0.5))+
labs(x = NULL, y = NULL, fill = NULL, title = "Energy Mix")+
theme_classic() + theme(axis.line = element_blank(),
axis.text = element_blank(),
axis.ticks = element_blank(),
plot.title = element_text(hjust = 0.5, color = "#666666"))+
facet_wrap(~Year)

Assign hline a different colour than other lines in the graph without using scale_colour_manual?

Fairly new to R so forgive me if this is a simple question. I have created a graph which tracks a loss ratio percentage by data provider. I assign the "data provider" lines colour using scale_colour_brewer 'blue'. In a previous iteration I had used scale_colour_manual to assign a colour to a data provider, however this can no longer be used as the data providers are now variables in the code using an IF statement to only include in the Shiny report if assigned a 1 earlier in the code.
I have tried to put a Horizontal line at .85 which I am trying to get the colour to be red. The scale_colour_brewer 'blue' portion of the code seems to overwrite the 'red' line, meaning it is a thick blue line and has the name 'red' in the legend. How do I correct this? Example code below:
LR_Graph_Plot <- ggplot() +
geom_hline(aes(yintercept = 0.85, color ="red"), size = 1.25) +
geom_line(data = LR_Graph(), aes(x = YM1_DATE, y = ELR, group = Data.Provider, color = Data.Provider), size = 0.75) +
# geom_hline(aes(yintercept = 0)) +
scale_colour_brewer("Blues") +
labs(y = "Loss Ratio (%)") +
ggtitle("Earned Loss Ratio: Loss Ratio Monthly split by Data Provider") +
scale_y_continuous(labels = scales ::percent) +
scale_x_date(breaks = "months", date_labels = "%Y-%m") +
theme_bw() +
theme(axis.title.x = element_blank(), legend.title = element_blank(), panel.border = element_blank(),
axis.line.y = element_line(color='black'), axis.line.x = element_line(color='black'),
legend.position = "right" , axis.text.x = element_text(angle = 90)) +
theme(
panel.background = element_rect(fill="#cccccc", color="#000000",size = 2, linetype = "solid"),
panel.grid.major = element_line(size = 0.5, linetype = "solid", colour = "white"),
panel.grid.minor = element_line(size = 0.5,linetype = "solid", colour = "white")
)
ELR_Graph_Plot <- ggplotly(LR_Graph_Plot)
Apologies if this is not clear or has been asked before. I'm fairly new to coding.
Move the color assignment out of the aesthetic mapping aes(). Then the line uses a fixed color and not the provided color scale.
Your line geom_hline(aes(yintercept = 0.85, color ="red"), size = 1.25) should be geom_hline(aes(yintercept = 0.85), color ="red", size = 1.25)

move legend title in ggplot2

I have been trying to shift my legend title across to be centered over the legend contents using the guide function. I've been trying to use the following code:
guides(colour=guide_legend(title.hjust = 20))
I thought of trying to make a reproducable example, but I think the reason it's not working has something to do with the above line not matching the rest of my code specifically. So here is the rest of the code I'm using in my plot:
NH4.cum <- ggplot(data=NH4_by_Date, aes(x=date, y=avg.NH4, group = CO2, colour=CO2)) +
geom_line(aes(linetype=CO2), size=1) + #line options
geom_point(size=3) + #point symbol sizes
#scale_shape_manual(values = c(1, 16)) + #manually choose symbols
theme_bw()+
theme(axis.text.x=element_text(colour="white"), #change x axis labels to white.
axis.title=element_text(size=12),
axis.title.x = element_text(color="white"), #Change x axis label colour to white
panel.border = element_blank(), #remove box boarder
axis.line.x = element_line(color="black", size = 0.5), #add x axis line
axis.line.y = element_line(color="black", size = 0.5), #add y axis line
legend.key = element_blank(), #remove grey box from around legend
legend.position = c(0.9, 0.6))+ #change legend position
geom_vline(xintercept=c(1.4,7.5), linetype="dotted", color="black")+ #put in dotted lines for season boundaries
scale_color_manual(values = c("#FF6600", "green4", "#0099FF"),
name=expression(CO[2]~concentration~(ppm))) + #manually define line colour
scale_linetype_manual(guide="none", values=c("solid", "solid", "solid")) + #manually define line types
scale_shape_manual(values = c(16, 16, 16)) + #manually choose symbols
guides(colour=guide_legend(title.hjust = 20))+
scale_y_continuous(expand = c(0, 0), limits = c(0,2200), breaks=seq(0,2200,200))+ #change x axis to intercept y axis at 0
xlab("Date")+
ylab(expression(Membrane~available~NH[4]^{" +"}~-N~(~mu~g~resin^{-1}~14~day^{-1})))+
theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank())+
geom_errorbar(aes(ymin = avg.NH4 - se.NH4, #set y error bars
ymax = avg.NH4 + se.NH4),
width=0.1)
I have tried doing the following instead with no luck:
guides(fill=guide_legend(title.hjust=20)
I have also adjusted the hjust value from values between -2 to 20 just to see if that made a difference but it didn't.
I'll try to attach a picture of the graph so far so you can see what I'm talking about.
I've looked through all the questions I can on stack overflow and to the best of my knowledge this is not a duplicate as it's specific to a coding error of my own somewhere.
Thank-you in advance!!
The obvious approach e.g.
theme(legend.title = element_text(hjust = .5))
didn't work for me. I wonder if it is related to this open issue in ggplot2. In any case, one manual approach would be to remove the legend title, and position a new one manually:
ggplot(mtcars, aes(x = wt, y = mpg, colour = factor(cyl))) +
geom_point() +
stat_smooth(se = FALSE) +
theme_bw() +
theme(legend.position = c(.85, .6),
legend.title = element_blank(),
legend.background = element_rect(fill = alpha("white", 0)),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank()) +
annotate("text", x = 5, y = 27, size = 3,
label = "CO[2]~concentration~(ppm)", parse = TRUE)
Output:

Overlay different datasets in same facetted plot in ggplot2

I need to gather two facet columns into one column with ggplot2.
In the following example, I need to overlay the content of the two columns DEG and RAN into one, while giving different colours to DEG and RAN data (small points and smooth line) and provide the corresponding legend (so I can distinguish them as they are overlayed).
I feel my code is not too, too far from what I need, but the relative complexity of the dataset blocks me. How to go about achieving this in ggplot2?
Here's my code so far:
require(reshape2)
library(ggplot2)
library(RColorBrewer)
fileName = paste("./4.csv", sep = "") # csv file available here: https://www.dropbox.com/s/bm9hd0t5ak74k89/4.csv?dl=0
mydata = read.csv(fileName,sep=",", header=TRUE)
dataM = melt(mydata,c("id"))
dataM = cbind(dataM,colsplit(dataM$variable,pattern = "_",names = c("NM", "ORD", "CAT")))
dataM$variable <- NULL
dataM <- dcast(dataM, ... ~ CAT, value.var = "value")
my_palette <- colorRampPalette(rev(brewer.pal(11, "Spectral")))
ggplot(dataM, aes(x=NR ,y= ASPL)) +
geom_point(size = .4,alpha = .5) +
stat_smooth(se = FALSE, size = .5) +
theme_bw() +
theme(plot.background = element_blank(),
axis.line = element_blank(),
legend.key = element_blank(),
legend.title = element_blank()) +
scale_y_continuous("ASPL", expand=c(0,0), limits = c(1, 7)) +
scale_x_continuous("NR", expand=c(0,0), limits = c(0, 100)) +
theme(legend.position="bottom") +
theme(axis.title.x = element_text(vjust=-0.3, face="bold", size=12)) +
theme(axis.title.y = element_text(vjust=1.5, face="bold", size=12)) +
ggtitle("Title") + theme(plot.title = element_text(lineheight=.8, face="bold")) +
theme(title = element_text(vjust=2)) +
facet_grid(NM ~ ORD)
Here's what it gives me right now:
Extra question: how come DEG/SF doesn't show a smooth line?
You can use the group aesthetic to define that data points with the same value of ORD belong together. You can also map aesthetics shape and color to this variable. You can also use . to specify that the facets are not split along a specific dimension.
I have made the changes to your code below after transforming NR and ASPL to numeric variables:
dataM$NR <- as.integer(dataM$NR)
dataM$ASPL <- as.numeric(dataM$ASPL)
ggplot(dataM, aes(x=NR ,y= ASPL, group=ORD, color=ORD)) +
geom_point(size = .7,alpha = .5, aes(shape=ORD)) + ## increased size
stat_smooth(se = FALSE, size = .5) +
theme_bw() +
theme(plot.background = element_blank(),
axis.line = element_blank(),
legend.key = element_blank(),
legend.title = element_blank()) +
scale_y_continuous("ASPL", expand=c(0,0), limits = c(1, 7)) +
scale_x_continuous("NR", expand=c(0,0), limits = c(0, 100)) +
theme(legend.position="bottom") +
theme(axis.title.x = element_text(vjust=-0.3, face="bold", size=12)) +
theme(axis.title.y = element_text(vjust=1.5, face="bold", size=12)) +
ggtitle("Title") + theme(plot.title = element_text(lineheight=.8, face="bold")) +
theme(title = element_text(vjust=2)) +
facet_grid(NM ~.)

How to change barplot in ggplot for R

I have a plot in ggplot that shows me for each category of "rating" the level of price in "bank" and "sistem". This is my code:
##fict
a<-c("rating1","rating2","rating3")
b<-c(1.2,1.2,1.3)
c<-c(1.6,1.4,1.6)
gg<-cbind('rating'=rep(a,2),'price'=c(b,c),'tipo'=rep(c("bank","sistem"),3))
gg<-as.data.frame(gg)
a<-rgb(red=150, green=191, blue=37, maxColorValue = 255)
b<-rgb(red=80, green=113, blue=14, maxColorValue = 255)
ggplot(gg, aes(x=tipo, y=price,width=1)) +
geom_bar(position='stack', stat='identity', fill=c(b,a), color='black') +
facet_wrap( ~ rating)+
theme_bw() + theme(axis.line = element_line(colour = "black"),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.border = element_blank(),
panel.background = element_blank(),
strip.background = element_rect(colour = 'white', fill = 'white', size = 3),
axis.title.y=element_text(vjust=0.19),
axis.title.x=element_text(vjust=0.19)
#strip.text.x = element_text(colour = 'red', angle = 45, size = 10, hjust = 0.5, vjust = 0.5, face = 'bold')
) + xlab("My x label") +
ylab("My y label") +
labs(title = 'difference')
This code generates my plot.
I'd like to change 3 things:
I'd like that the labels rating shows in the bottom
I'd like that the "bank" and "sistem" labels disappear and change it with the legend with colors for bank and sistem.
If it's possible also put the legend under the x-axis title in horizontal way
Thank you
Upgrade comment to an answer.
library(ggplot2)
# your data - tweaked the code - there is no need to cbind within data.frame
# and names do not need to be in quotes
gg <- data.frame(rating=rep(c("rating1","rating2","rating3"),2),
price=c(c(1.2,1.2,1.3),c(1.6,1.4,1.6)),
tipo=rep(c("bank","sistem"),3))
a <- rgb(red=150, green=191, blue=37, maxColorValue = 255)
b <- rgb(red=80, green=113, blue=14, maxColorValue = 255)
# Plot
# use position dodge to get the bars side-by-side
# theme_classic removes grid lines and uses theme_bw()
# scale_fill_manual to manually specify the colours - by using fill = tipo in the
# aesthetic call of ggplot a legend will be generated
# scale_y_continuous - using expand starts the axis at exactly zero
ggplot(gg, aes(x=rating, y=price, fill=tipo)) +
geom_bar(position='dodge', stat='identity', color='black') +
theme_classic() +
scale_fill_manual(values = c(b,a)) +
scale_y_continuous(limit=c(0,2), expand=c(0,0)) +
labs(title = 'difference', x = "My x label", y = "My y label") +
theme(
axis.title.y=element_text(vjust=0.19),
axis.title.x=element_text(vjust=0.19) ,
legend.position = "bottom",
legend.title=element_blank())

Resources