R: ggplot2 scalebar in miles - r

I'v been trying to find a good function to create a scalebar in miles for some maps I made. However, all the packages I have found only allow you to have the scalebar in km. I need it in miles. I came across the scale_bar function from
devtools::install_github("3wen/legendMap")
which allows you to change the units to miles. I have been playing around with the arguments to get it to work all morning but nothing seems to make it work. I would appreciate it if anyone can help me resolve this issue or know of any packages that can do this. Thanks in advance.
graph1<-ggplot()+
geom_polygon(data=middlestates,colour="black",fill="#D3D3D3",aes(x=long,y=lat,group=group))+
geom_polygon(data=df,colour="black",aes(x=long,y=lat,group=group,fill=ALG))+
ggtitle("Figure 2.2A: Assessment Results for\nGeneral Aquatic Life Use, Spatial Extent")+
xlab("")+
ylab("")+
coord_cartesian(xlim=c(200000.732,905000.646), ylim=c(-5812.321,900000.543))+
#ggsn::scalebar(df,location="bottomleft",dist = 50,st.dist=0.02,st.size=3, height=0.01)+
scale_fill_manual("Aquatic Life Designated\nUse 2014 Assessment",values=c((values=c(colors))))+
cowplot::background_grid(major= "none",minor = "none") +
theme(axis.text.x = element_blank(), axis.ticks.x = element_blank(),
axis.text.y = element_blank(), axis.ticks.y = element_blank(),
axis.line = element_blank(),
panel.background = element_blank(),
legend.position=c(0.8,0.2),
panel.border = element_rect(fill=NA),
legend.background = element_blank(),
legend.text = element_text(size=12),
legend.title = element_text(colour="black", size=12, face="bold"),
plot.title=element_text(size=15, face="bold",hjust=0.5))
graph1+scale_bar(lon =200000.732, lat = -5812.321,distance_lon = 1,distance_lat = 5,distance_legend = 2,dist_unit = "mi", orientation = FALSE)
The plot I'm getting (scale bar in bottom left corner):

Related

R function scale_fill_manual printing wrong legend

I've tried everywhere to find a solution for my problem, without success.
In my company we have a R project, where we use our own colors to print the plots. One of our colleagues is having trouble with it, and we can't figure it out why (since the plot is working fine for all other colleagues and we all -including her- have the same version of R, R Studio and packages).
The problem is when she is printing the plots, the legend is totally weird and printing way more information (from other plots). We tried everything we could think of...
Unfortunetely I can't display the whole code/plots since is confidential information, but I hope this can help:
correct plot should look like this
incorrect plot look like this
The code is more or less, this one:
ggplot(df , aes(x = factor(columnA), y = value ,fill=factor(variable))) +
geom_bar(stat='identity',position="stack")+
labs(x=element_blank(),y="label")+
scale_x_discrete(breaks = df$columnA ,labels=str_wrap(df$columnB, 15) ) +
ggtitle("Confidential tile") +
theme_ourown + #we have our own theme as well
theme(panel.grid.major = element_line(colour = "grey90"),
axis.ticks = element_blank(), axis.title = element_blank(), axis.text.x = element_text(colour = "grey30"),
axis.text.y = element_blank(), legend.title = element_blank(), plot.title = element_text(hjust = 0.5),
legend.text = element_text(size = rel(1.33)), legend.key.size = unit(1, "cm")) +
scale_fill_manual(values = report_colours) + #here is our colors
coord_polar()
Well, thank you all in advance!

Adjusting Title & Figsize in R

For this problem I am required to use ggplot2 and ggplot2 only. I have a barplot similar to the one below:
I would like to insert a title on the upper left corner but somehow it keeps ending up in the wrong place.
geom_text(stat='count', aes(label = ..count..), vjust = -1) +
theme(panel.background = element_blank(),
axis.text.y = element_blank(),
axis.title.y = element_text(),
axis.ticks.y = element_blank(),
axis.title.x = element_blank(),
plot.margin = margin(1,1,1,1),
panel.border = element_rect(fill = NA))
Furthermore I run into the problem of reshaping the plot. I would like the height of the plot to be much smaller but have the same width. Whenever I try it myself i can crop the plot but parts of the biggest bar are being cropped of aswell.
Can anyone help me?

size argument not working in geom_errorbar in ggplot2

I am trying to create a graph of value ranges so that they can be compared to a unique range (represented by a gray rectangle in the graph). I got the graph to work just like I wanted to it but I cannot effectively change the line weight of the error bars that I am using to represent the value ranges. The code it below with example figures.
### Graph with default line weights
ggplot(data=droplevels(wght2[which(wght2$Zone!="Oahu"),]), aes(x=wght2$num[wght2$Zone!="Oahu"], y=(wght2[which(wght2$Zone!="Oahu"),4]+wght2[which(wght2$Zone!="Oahu"),4+3])/2,
group= wght2[which(wght2$Zone!="Oahu"),2], color= wght2[which(wght2$Zone!="Oahu"),2])) +
geom_errorbar(aes(ymin=wght2[which(wght2$Zone!="Oahu"),4], ymax=wght2[which(wght2$Zone!="Oahu"),4+3], width=0.3, color=wght2[which(wght2$Zone!="Oahu"),2])) +
geom_rect(ymin=wght2[8,4], ymax=wght2[8,4+3], xmin=0.5, xmax=6+0.5, fill="gray25", linetype=0, alpha=0.07)+
scale_color_manual(values=c("forestgreen","deepskyblue3","gold"))+
scale_x_continuous(labels=levels(wght2$Zone), breaks=c(1,2,3.5,5.5))+
labs(x="Zone",y=measure3[4]) +
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(),
legend.text = element_text(size = 16),
legend.title = element_text(size=16),
axis.text = element_text(size = 16,colour="black"),
axis.title = element_text(size = 18)) +
theme(legend.position="topright")
### My attempt to change line weights
ggplot(data=droplevels(wght2[which(wght2$Zone!="Oahu"),]), aes(x=wght2$num[wght2$Zone!="Oahu"], y=(wght2[which(wght2$Zone!="Oahu"),4]+wght2[which(wght2$Zone!="Oahu"),4+3])/2,
group= wght2[which(wght2$Zone!="Oahu"),2], color= wght2[which(wght2$Zone!="Oahu"),2])) +
geom_errorbar(aes(ymin=wght2[which(wght2$Zone!="Oahu"),4], ymax=wght2[which(wght2$Zone!="Oahu"),4+3], width=0.3, size=0.5, color=wght2[which(wght2$Zone!="Oahu"),2])) +
geom_rect(ymin=wght2[8,4], ymax=wght2[8,4+3], xmin=0.5, xmax=6+0.5, fill="gray25", linetype=0, alpha=0.07)+
scale_color_manual(values=c("forestgreen","deepskyblue3","gold"))+
scale_x_continuous(labels=levels(wght2$Zone), breaks=c(1,2,3.5,5.5))+
labs(x="Zone",y=measure3[4]) +
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(),
legend.text = element_text(size = 16),
legend.title = element_text(size=16),
axis.text = element_text(size = 16,colour="black"),
axis.title = element_text(size = 18)) +
theme(legend.position="topright")
As you can see from my code when I include the 'size' argument in the 'aes' function of geom_errorbar, the line weights become huge even though I set it at the default which is 0.5.
Any advice on how to change the line weights in geom_errorbar would be much appreciated. I know I could just draw each line in with geom_segment but feel like using geom_errorbar should work and want to know why it is not. Thanks!

ggplot legend labels and colors

I am struggling with ggplot to produce the legend of this figure. For now, I am only doing for one map, when it works I'l produce the four maps in the same plot.
I would like a legend like this: bottom, title in the center and above the scale, labels and colors, and omit the NA values.
Here is my code:
Reading the shapefile and installing a new variable
map_ev#data$id = rownames(map_ev#data)
map_ev.points = fortify(map_ev, region="id")
map_ev.df = join(map_ev.points, map_ev#data, by="id")
map_ev.df$median_norm = map_ev.df$median / map_ev.df$VOM
Vector with theme opts for ggplot
theme_opts <- list(theme(panel.grid.minor = element_blank(),
panel.grid.major = element_blank(),
panel.background = element_blank(),
panel.border = element_blank(),
axis.line = element_blank(),
axis.text.x = element_blank(),
axis.text.y = element_blank(),
axis.ticks = element_blank(),
axis.title.x = element_blank(),
axis.title.y = element_blank(),
plot.title = element_text(size=12, hjust=0.5),
legend.position = "bottom",
legend.title=element_blank()))
Installing the variable breaks
map_ev.df$median_norm <- cut(map_ev.df$median_norm, breaks=c(-200, -100, -50, -20, -5, 0, 5, 20, 50, 100, +200))
Checking the breaks
levels(map_ev.df$median_norm)
Colors to be used
color_map <- palette(c("#5b2e07", "#904d07", "#b98436", "#dfc27e", "#f6e8c3",
"#c9e9e4", "#84cdc4", "#3c958f", "#01675a", "#073a31"))
ggplot code
ggplot(map_ev.df) +
aes(long,lat,group=group,fill=median_norm, color=median_norm) +
geom_polygon() + geom_path(color="black") +
labs(title="Equivalent variation") + coord_equal() +
theme_opts
For now I am getting this figure:
Thanks all, I appreciate your help!
I just noticed you wanted manual colours for the fill. You can use:
myscale <- c("(-1,10]"="#BBDF27", "(10,20]"="#43BF71", "(20,30]"="#21908C", "(30,50]"="#35608D", "(50,101]"="#482576", "(101,300]"="#ffeeed")
combined with:
scale_fill_manual(values=myscale,na.value="#e0e0e0",name="",labels=c("<10","10 - 20","20 - 30","30 - 50", ">50","Estimate", "NA"))
where scale_fill manual replaces scale_fill_brewer in the other answer.
Just replace the colour and label values with your own. The values that need to go into myscale are shown when you plot your map without any labels. Good luck!
The reason you don't have a title, is because you never specified one, and if you did, you're deleting it again by writing legend.title=element_blank() in theme. Instead I rewrote it to specify the title should be centered. Using guides(colour = guide_legend(title.position = "top"),fill = guide_legend(title.position = "top",nrow=1,byrow=TRUE)) I set the position to "top" and made sure it will only be one row of legend items. (I left colour= here in case you do need it).
You also seem to want black borders, this means I deleted all colour= since that specifies the colour of the borders.
I've added a scale_fill_brewer, there are more color palettes available. Within this you can specify your legend title and the appearance of your legend labels. These need to be manually adjusted every time you change your input data, by the way.
I don't know how to remove the legend item for NA, sorry.
This is the total code I came up with:
ggplot(map_ev.df) +
aes(long,lat,group=group,fill=median_norm) +
scale_fill_brewer(palette="BrBG",name= "Title of legend",labels=c("-200 - -100","-100 - 50","-5 - 0","0 - 5", "label for NA"))+
geom_polygon() + geom_path(color="black") +
labs(title="Equivalent variation") + coord_equal() +
theme(panel.grid.minor = element_blank(),
panel.grid.major = element_blank(),
panel.background = element_blank(),
panel.border = element_blank(),
axis.line = element_blank(),
axis.text.x = element_blank(),
axis.text.y = element_blank(),
axis.ticks = element_blank(),
axis.title.x = element_blank(),
axis.title.y = element_blank(),
plot.title = element_text(size=12, hjust=0.5),
legend.position = "bottom",
legend.direction = "horizontal",
legend.title = element_text(hjust=0.5))+
guides(colour = guide_legend(title.position = "top"),fill = guide_legend(title.position = "top",nrow=1,byrow=TRUE))
Using some data of my own for the fill:
map

Avoiding over-printing for publication quality figures

I am trying to create a full-page figure to publish. The figure looks great on my screen device using Cairo. I've struggled and struggled to get it saved nicely as a file that I can submit. I'm close, as well as I can articulate it, my points and lines just blob together. It's not a resolution issue because as I zoom in, everything looks better and better.
Here is how I make one panel (drawing from two different data frames):
ggplot()+
geom_line(aes(df1$Date, y=df1$sw_10), colour = "black", size=.25) +
geom_point(aes(df2$Date, y=df2$sw_10),fill="white",colour="blue",pch=21, size=1) +
scale_fill_manual(values=c("white"))+
ylim(0.1,0.4)+
theme(panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.background = element_blank(),
axis.line = element_line(),
legend.position='none', legend.title=element_blank(),
legend.text = element_text(size=12),
axis.title.x = element_blank(),
axis.title.y = element_blank(),
axis.text.x = element_blank(),
axis.text.y = element_text(colour="black", size=12))
Then I put them together with grid and output as an eps:
postscript("figure.eps", width=8.5, height = 11)
print(fig)
dev.off()
And here is the result:
figure
or, as the .eps: https://www.dropbox.com/s/zo3rsnv7tuvg1a6/tryit.eps?dl=0
Is there any obvious way to improve this?

Resources