1 year ago
#357620
meteo_96
How to save a figure in R within the code
I am plotting 2 probability density functions of observed and modeled fields. I have this code below:
# Import libraries
library("stringr")
library(ggplot2)
#EXTENDED Observations with reanalysis obervatory 085320
# load in the text files and convert to dataframe
directory = '/Users/jacob/Desktop/Master Meteorologia/PE/Datos/Lisboa/wind/00_Observed/Extended/Observed-Wind-Lisboa_Extended/'
filename = '085320_Wind_Extended.txt'
directory2 = '/Users/jacob/Desktop/Master Meteorologia/PE/Datos/Lisboa/wind/MPI-ESM-MR/Historical/'
filename2 = 'Wind_MPI-ESM-MR_Historical_085320.txt'
extFile = read.delim(str_c(directory,filename), header = FALSE, col.names=c("Year", "Month", "Day", "WindMagn"))
histFile = read.delim(str_c(directory2,filename2), header = FALSE, col.names=c("Year", "Month", "Day", "WindMagn"))
# Extract vecto==wind from both cases
windMagnExt = extFile$WindMagn
windMagnHist = histFile$WindMagn
### PDF observed and modelled
d= density(windMagnExt)
e= density(windMagnHist)
#png('/Users/jacob/Desktop/Master Meteorologia/PE/Figures/windMagnObsHist_PDF.png', width = 1000, height=1000, units='px' ,res=700, pointsize = 12)
plot(d, main="PDF of observed and modelled wind for Obs. 085320", col="red")
lines(e, col="blue" )
legend("topright", legend=c("Observed", "Modelled"),
col=c("red", "blue"), lty=1:2, cex=0.8)
grid()
#dev.off()
It gives me this type of plot:
However, there are 2 things I still want to be done.
In the legend, the modelled field is a dashed line when it is not. How do I change this.
I try to uncomment 2 lines png() and dev.off() to save the figure within the code and not have to use the export button in RStudio. I do it as follows:
### PDF observed and modelled
d= density(windMagnExt)
e= density(windMagnHist)
png('/Users/jacob/Desktop/Master Meteorologia/PE/Figures/windMagnObsHist_PDF.png', width = 15, height=10, units='px' ,res=700, pointsize = 12)
plot(d, main="PDF of observed and modelled wind for Obs. 085320", col="red")
lines(e, col="blue" )
legend("topright", legend=c("Observed", "Modelled"),
col=c("red", "blue"), lty=1:2, cex=0.8)
grid()
dev.off()
But then it gives me this error. I tried saving other figures using this before, but now it tells me that figure margins are too large
EDIT:
Based on D.J's comment below i tried running png() without any parameters:
### PDF observed and modelled
d= density(windMagnExt)
e= density(windMagnHist)
png('/Users/jacob/Desktop/Master Meteorologia/PE/Figures/windMagnObsHist_PDF.png', res=300)
plot(d, main="PDF of observed and modeled wind for Obs. 085320", col="red", xlab='Wind speed (m/s)')
lines(e, col="blue" )
legend("topright", legend=c("Observed", "Modeled"),
col=c("red", "blue"), lty=1:1, cex=0.8)
grid()
dev.off()
It gives me the plot I want but, when adding the parameter res=300, I still get the same error as above.
Any help? Thanks!
r
density-plot
0 Answers
Your Answer