I'm very new to R so I apologise in advance if this is a very basic question.
I'm trying to plot a graph showing discharge and suspended sediment load (SSL). However, I want to make it clear that the bar plot represents discharge, and the line graph represents SSL. I had two ideas:
color the label for discharge and SSL to correspond to the bar graph and line graph respectively, so the reader intuitively knows which one belongs to which. but ggplot2 doesn't allow me to do this because it'll colour both y axes the same color.
build a legend that indicates clearly that the red line belongs to SSL, blue box plot belongs to discharge. There is a post here which does something similar but I can't seem to achieve it. I would greatly appreciate it if someone could help me out.
This is what my graph looks like now.
This is my script:
library(ggplot2)
library(gridExtra)
library(RColorBrewer)
library(tibble)
P_Discharge <- Pyay$Mean.monthly.discharge
P_MaxTemp <- Pyay$Mean.monthly.max.temperature
P_MinTemp <- Pyay$Mean.monthly.minimum.temperature
P_Rain <- Pyay$Max.monthly.rainfall
P_SSL <- Pyay$Mean.suspended.sediment.load
#reorderingthemonths
Pyay$Month <- factor(Pyay$Month,
levels=c("Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"))
#PlottingdischargeandSSL
Pgraph1 <- ggplot(Pyay, aes(x=Month, group=2))
Pgraph1 <- Pgraph1 + geom_bar(aes(y=P_Discharge), stat="identity", fill="blue")
Pgraph1 <- Pgraph1 + geom_line(aes(y=P_SSL), colour="red", size=1) +
labs(y=expression(Q/(m^{3}))) +
labs(x="")
#addingsecondaxis
Pgraph1 <- Pgraph1 + scale_y_continuous(sec.axis=sec_axis(~., name=expression(
Suspended~sediment~load~(10^{6}~t))))
#colouringaxistitles
Pgraph1 <- Pgraph1 + theme(axis.title.x=element_blank(),
axis.title.y=element_text(size=14),
axis.text.x=element_text(size=14))
Pgraph1
Data
Pyay <- tibble::tribble(
~Month, ~Mean.monthly.discharge, ~Mean.monthly.max.temperature, ~Mean.suspended.sediment.load, ~Max.monthly.rainfall, ~Mean.monthly.minimum.temperature,
"Jan", 8.528, 32.2, 3.407, 1.5, 16.2,
"Feb", 6.316, 35.1, 2.319, 0.9, 17.8,
"Mar", 7, 37.6, 2.587, 5.1, 21.2,
"Apr", 8.635, 38.7, 3.573, 27.3, 24.7,
"May", 12.184, 36, 5.785, 145.1, 25.6,
"Jun", 30.414, 31.9, 21.811, 234.8, 24.8,
"Jul", 70.753, 31, 70.175, 198, 24.8,
"Aug", 79.255, 31, 81.873, 227.5, 24.7,
"Sep", 67.079, 32.3, 65.798, 205.7, 24.6,
"Oct", 53.677, 33.5, 47.404, 124, 24.2,
"Nov", 22.937, 32.7, 14.468, 56, 21.7,
"Dec", 12.409, 31.5, 5.842, 1.5, 18.1
)
str()
,head()
or screenshot)? You can use thereprex
anddatapasta
packages to assist you with that. See also Help me Help you & How to make a great R reproducible example? – Doublejointed