Pesky border around a grob inset map - r

I made this map and it's nearly perfect except for the inset map has this pesky white borer around it. I would like for the inset to just have the black line border of the actual panel border, but not that white background that's coming along with it. Additionally, my panel.grid element is not displaying above the land mass I have plotted, and would like for it to display above the land mss (pictured in the main map in light gray). I have my panel.grid = element_line(color = "darkgray") in my main map, but it's still not displaying the way I intended. The same goes for my scale bar and my north arrow. Here is a screenshot of my plot:
And this is the code that I used to generate my map:
MainMap <- ggplot(QOI) +
geom_sf(aes(fill = quadID)) +
scale_fill_manual(values = c("#6b8c42",
"#70b2ae",
"#d65a31")) +
labs(fill = "Quadrants of Interest",
caption = "Figure 1: Map depicting the quadrants in the WSDOT project area as well as other quadrants of interest in the Puget Sound area.")+
ggtitle("WSDOT Project Area and Quadrants of Interest") +
geom_sf(data = BCWA_land) +
xlim (-123.1, -121.4) +
ylim (47.0, 48.45) +
theme_bw()+
theme(panel.grid = element_line(color = "darkgray"),
legend.text = element_text(size = 11, margin = margin(l = 3), hjust = 0),
legend.position = c(0.95, 0.1),
legend.justification = c(0.85, 0.1),
legend.background = element_rect(colour = "#3c4245", fill = "#f4f4f3"),
axis.title = element_blank(),
plot.title = element_text(face = "bold", colour = "#3c4245", hjust = 0.5, margin = margin(b=10, unit = "pt")),
plot.caption = element_text(face = "italic", colour = "#3c4245", margin = margin(t = 7), hjust = 0, vjust = 0.5))
MainMap
InsetRect <- data.frame(xmin=-123.2, xmax=-122.1, ymin=47.02, ymax=48.45)
InsetMap <- ggplotGrob( ggplot( quads) +
geom_sf(aes(fill = "")) +
scale_fill_manual(values = c("#eefbfb"))+
geom_sf(data = BCWA_land) +
scale_x_continuous(expand = c(0,0), limits = c(-124.5, -122.0)) +
scale_y_continuous(expand = c(0,0), limits = c(47.0, 49.5)) +
geom_rect(data = InsetRect,aes(xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax),
color="#3c4245",
size=1.25,
fill=NA,
inherit.aes = FALSE) +
theme_bw()+
theme(legend.position = "none",
panel.grid = element_blank(),
axis.title = element_blank(),
axis.text = element_blank(),
axis.ticks = element_blank(),
panel.background = element_blank()))
InsetMap
Figure1 <- MainMap +
annotation_custom(grob = InsetMap, xmin = -122.2, xmax = -121.3,
ymin = 47.75, ymax = 48.5) +
scalebar(x.min = -122.7, x.max = -122.5, y.min = 46.95, y.max = 47.1, location = "bottomright",
transform = TRUE, dist = 10, dist_unit = "km", st.size = 2, st.bottom = TRUE)
Figure1
In the inset map code, I had set the panel.background = element_blank() so I'm not sure why I'm still getting a white background/border around my inset.
Please let me know if you need the data that I used to generate these maps. It's a larger file and so the character limit on SO limits what I can put up. Even if I trim the data down, because they are polygon shape files a single data row is pretty cumbersome to share.
Any insight would be much appreciated!

Related

How to add polygon in ggplot2 along with raster? Polygon is missing from final plot after ggplot

I have a stack of raster's and suppose to find the mean of it. I have done it. Now, I want to add polygon on the mean of raster image that I got. Then, I wants to save and make it colorful by using ggplot2 code. But I don't understand how to and where add polygon in ggplot2.
fs <- list.files(path="directory.tiff", pattern =
"tif$", full.names = TRUE)
s<- raster::stack(fs)
pg <- readOGR("parks.shp")
se1 <- calc(s, fun = mean)
plot(se1)
plot(pg, add= T )
They give me this attached below picture, Parks overlay on the mean of raster's. Its fine till now.
But when I used ggplot to change its color scheme. They gave me desired pattern what I want, but the problem is parks polygons doesn't overlay on the final picture (attached below after code what I get). So can anyone tell me where I need to change the code in ggplot to get park shp overlay on the picture 2.
conti_col_pal <- pnw_palette("Bay",10,type="continuous")
binary.cols <- c("1" = conti_col_pal[10], "0" = "white")
cv.df <- as.data.frame(rasterToPoints(se1))
##above I give the comand of se1 when I add pg here instead it give me error.
p_cv <- ggplot() +
coord_fixed() +
geom_raster(data = xy_FONDO, aes(lon, lat, fill = r)) +
scale_fill_gradient(low = "gray56", high = "gray56", na.value = NA, guide = FALSE) +
new_scale("fill") +
geom_raster(data = cv.df, aes(x, y, fill = layer))+
scale_fill_gradientn(colours = conti_col_pal,
breaks = seq(-1, 7, 2), limits = c(0, 10))+
annotate(geom = "text", x = lonmin+2, y = latmax-2, vjust = 1, hjust = 0,
label = "",
color = "black", angle = 0, size=4)+
scale_x_continuous(limits = c(lonmin, lonmax), expand = c(0, 0)) +
scale_y_continuous(limits = c(latmin, latmax), expand = c(0, 0))+
theme_bw(base_family="")+
theme(
plot.margin = margin(0, 0, 0, 0, "cm"),
#panel.background = element_rect(fill = col_pal_binary[1], colour = col_pal_binary[1], size
= 0.5, linetype = "solid"),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
axis.title.x=element_blank(),
axis.title.y=element_blank(),
axis.text.x=element_blank(),
axis.text.y=element_blank(),
axis.ticks.x=element_blank(),
axis.ticks.y=element_blank(),
legend.background = element_rect(fill=NA, size=0.3, linetype="solid", color=NA),
legend.position = c(0.8, 0.35),
legend.title= element_blank(),
legend.text = element_text(colour = "black", size = 12, angle = 0),
legend.direction = "vertical", ##vertical; horizontal
legend.title.align=0.5)+
guides(fill = guide_colorbar(## label.position = "bottom",
## title.position = "left",
label.vjust=0,
# draw border around the legend
frame.colour = "black",
barwidth = 1.5,
barheight = 8))
tiff(filename = "bay.tiff", res = 600,
width = 4080, height = 3200, compression = "lzw")
grid.arrange(p_cv,
ncol = 1)
dev.off()
After defining the raster "d.f" do same for pg but use function fortify to do and similarly after "geom_raster" do "geom_polygon" to introduce the polygon in ggplot.

Minimize or remove discontinuous axis white spaces or ideally, alter axis scaling - trying to find a solution - R

I have been trying to create a graph that has non-linear (and non-log) based scaling on the axis. Ideally the graph would not be discontinuous. It is hard to explain so I will show it with pictures. My current graph uses a ln transformed scale to give:
The problem is most of my data is log normally skewed, and I would ideally like to have the large majority of the data centered on the graph. If I could do this perfectly, the axis would scale like:
Upper 20% of graph = 1,001-40,000
Mid 30% of graph = 201-1,000
Lower 50% of graph = 1-200
To attempt this, I have tried the package: gg.gap. I thought using a discontinuous axis would be good, but that introduces white spaces. From what I can tell, these cannot be minimized. I have also tried to facet three graphs vertically. Using cowplots I have achieved this:
This is much closer to what I want, but the problem is that the white space still exist, and the way that the plot margins work, it ends up cutting some data point off in half, leaving weird half circles at the extremities. - Note: I fixed this now with " coord_cartesian(clip = "off")", the points are no longer clipped.
To solve this I am at a loss and thought I would reach out for some help. Here is a minimal reproducible code (still long but it shows everything that produces each graph).
#Generate Random Data set:
set.seed(1)
graphdata <-as.data.frame(rlnorm(29000, meanlog = 4.442651, sdlog = 0.85982))
colnames(graphdata)[1] <- "values"
high_values <- as.data.frame(rlnorm(1000, meanlog = 9.9, sdlog = 0.85))
colnames(high_values)[1] <- "values"
graphdata <- rbind(graphdata,high_values)
graphdata$values <- round(graphdata$values, digits = 0)
#Current Plot
#I used 'Trans = 'log'' to set the axis to a natural log scale. It has worked until my data have become large enough that I need to change the scaling of the axis for better visibility.
library(tidyverse)
graph <- ggplot(graphdata, aes(y = values, x=1))+
geom_jitter(aes(colour = cut(values, c(0,100,200,Inf))), alpha = 0.2, size = 0.5)+
scale_color_manual(values = c("#F0CF19","#F07C0B", "#D52828"))+
scale_y_continuous(breaks = c(0,20,50,100,200,500,1000,2000,5000,10000,20000,40000), trans='log', limits = c(14, 40001), expand = c(0, 0))+
labs(y = "Values", x = NULL)+
scale_x_continuous(expand = c(0.01, 0))+ coord_cartesian(clip = "off")+
theme_classic()+
theme(legend.position = "none",
axis.text.x = element_blank(),
axis.ticks.x = element_blank(),
axis.line.x = element_blank())
graph
#My attempt to get an altered axis arrangement - using multiple plots and stacking them:
graph1 <- ggplot(graphdata, aes(y = values, x=1))+
geom_jitter(aes(colour = cut(values, c(0,100,200,Inf))), alpha = 0.2, size = 0.5)+
scale_color_manual(values = c("#F0CF19","#F07C0B", "#D52828"))+
scale_y_continuous(breaks = c(0,20,50,100,200), trans='log', limits = c(14, 200), expand = c(0, 0))+
labs(y = NULL, x = NULL)+
scale_x_continuous(expand = c(0.01, 0))+
theme_classic()+ coord_cartesian(clip = "off")+
theme(legend.position = "none",
axis.text.x = element_blank(),
axis.ticks.x = element_blank(),
axis.line.x = element_blank(),
plot.margin = margin(t=0, unit = "pt"))
graph1
graph2 <- ggplot(graphdata, aes(y = values, x=1))+
geom_jitter(aes(colour = cut(values, c(0,100,200,Inf))), alpha = 0.2, size = 0.5)+
scale_color_manual(values = c("#F0CF19","#F07C0B", "#D52828"))+
scale_y_continuous(breaks = c(500,1000), trans='log', limits = c(201, 1000), expand = c(0, 0))+
labs(y = "Values", x = NULL)+
scale_x_continuous(expand = c(0.01, 0))+
theme_classic()+ coord_cartesian(clip = "off")+
theme(legend.position = "none",
axis.text.x = element_blank(),
axis.ticks.x = element_blank(),
axis.line.x = element_blank(),
plot.margin = margin(t=0, unit = "pt"))
graph2
graph3 <- ggplot(graphdata, aes(y = values, x=1))+
geom_jitter(aes(colour = cut(values, c(0,100,200,Inf))), alpha = 0.2, size = 0.5)+
scale_color_manual(values = c("#F0CF19","#F07C0B", "#D52828"))+
scale_y_continuous(breaks = c(10000,20000,40000), trans='log', limits = c(1001, 40001), expand = c(0, 0))+
labs(y = NULL,x = NULL)+
scale_x_continuous(expand = c(0.01, 0))+
theme_classic()+ coord_cartesian(clip = "off")+
theme(legend.position = "none",
axis.text.x = element_blank(),
axis.ticks.x = element_blank(),
axis.line.x = element_blank(),
plot.margin = margin(t=0, unit = "pt"))
graph3
#Using Cowplot, I stichted together three panels to make one graph that is close to what I want. But the problem lies with the white space between the panels. I want to get rid of it. Also, this method leads to some points being cut-off, leaving wierd half circles.
library(cowplot);library(grid); library(egg)
graph4 <- cowplot::plot_grid(graph3, graph2, graph1, align = "v", ncol = 1, rel_heights = c(0.25,0.25,0.5))
graph4 <- set_panel_size(graph4, width = unit(7, "cm"), height = unit(6, "cm"))
grid.newpage()
grid.draw(graph4)
Thanks!
New, non-clipped image:
It looks like I needed to add in a layer of 'NULL' graphs to adjust the spacing of the white space. I made sure that my plot margins were 0 for top and bottom and then added in a NULL graph and adjusted the spacing to be negative. Here is the adjusted code:
#Generate Random Data set:
set.seed(1)
graphdata <-as.data.frame(rlnorm(29000, meanlog = 4.442651, sdlog = 0.85982))
colnames(graphdata)[1] <- "values"
high_values <- as.data.frame(rlnorm(1000, meanlog = 9.9, sdlog = 0.85))
colnames(high_values)[1] <- "values"
graphdata <- rbind(graphdata,high_values)
graphdata$values <- round(graphdata$values, digits = 0)
graph1 <- ggplot(graphdata, aes(y = values, x=1))+
geom_jitter(aes(colour = cut(values, c(0,100,200,Inf))), alpha = 0.2, size = 0.5)+
scale_color_manual(values = c("#F0CF19","#F07C0B", "#D52828"))+
scale_y_continuous(breaks = c(0,20,50,100,200), trans='log', limits = c(14, 200), expand = c(0, 0))+
labs(y = NULL, x = NULL)+
scale_x_continuous(expand = c(0.01, 0))+
theme_classic()+
coord_cartesian(clip = "off")+
theme(legend.position = "none",
axis.text.x = element_blank(),
axis.ticks.x = element_blank(),
axis.line.x = element_blank(),
axis.title.x = element_blank(),
axis.title.y = element_blank(),
plot.margin = margin(0,0,0,0))
graph1
graph2 <- ggplot(graphdata, aes(y = values, x=1))+
geom_jitter(aes(colour = cut(values, c(0,100,200,Inf))), alpha = 0.2, size = 0.5)+
scale_color_manual(values = c("#F0CF19","#F07C0B", "#D52828"))+
scale_y_continuous(breaks = c(500,1000), trans='log', limits = c(201, 1000), expand = c(0, 0))+
labs(y = "Longer title Values", x = NULL)+
scale_x_continuous(expand = c(0.01, 0))+
theme_classic()+
coord_cartesian(clip = "off")+
theme(legend.position = "none",
axis.text.x = element_blank(),
axis.ticks.x = element_blank(),
axis.line.x = element_blank(),
axis.title.x = element_blank(),
plot.margin = margin(0,0,0,0))
graph2
graph3 <- ggplot(graphdata, aes(y = values, x=1))+
geom_jitter(aes(colour = cut(values, c(0,100,200,Inf))), alpha = 0.2, size = 0.5)+
scale_color_manual(values = c("#F0CF19","#F07C0B", "#D52828"))+
scale_y_continuous(breaks = c(10000,20000,40000), trans='log', limits = c(1001, 40001), expand = c(0, 0))+
labs(y = NULL,x = NULL)+
scale_x_continuous(expand = c(0.01, 0))+
theme_classic()+
coord_cartesian(clip = "off")+
theme(legend.position = "none",
axis.text.x = element_blank(),
axis.ticks.x = element_blank(),
axis.line.x = element_blank(),
axis.title.x = element_blank(),
axis.title.y = element_blank(),
plot.margin = margin(0,0,0,0))
graph3
#Using Cowplot, I stichted together three panels to make one graph that is close to what I want. But the problem lies with the white space between the panels. I want to get rid of it. Also, this method leads to some points being cut-off, leaving wierd half circles.
library(cowplot);library(grid)
graph4 <- cowplot::plot_grid(graph3,NULL, graph2, NULL,graph1, align = "v", ncol = 1, rel_heights = c(0.25,-0.01,0.25,-0.01,0.5)) #adjust spacing with the negative values here.
graph4 <- set_panel_size(graph4, width = unit(7, "cm"), height = unit(6, "cm"))
grid.newpage()
grid.draw(graph4)
I end up with this graph:
Overall I am happy that I can adjust the spacing now. However, this brings in another issue of axis title. It looks like the layering makes the last listed graph as the top most graph. The title from the middle graph is cutoff from the bottom graph. Here is what I mean (title is supposed to read "longer title Values"):
So that is the next hurdle, but may be another question that I have to ask in a separate post.

How to draw an empty ggplot with just the legend?

My question is very similar to this question, but it's not the same.
I am looking for a way to create an empty ggplot with just the legend. However, in contrast to the autohor of the question I linked at the top, I actually need to create just the legend with no plot area included in the image.
I tried the following code:
ggplot(NULL, aes(color = ""))+
geom_blank()+
scale_color_manual(values = "black", labels = "Something")+
guides(color = guide_legend())+
theme(legend.box.background = element_rect(color = "black"))
But I'm getting the opposite of what I want - I am getting an empty plot area with no legend, like this:
And I would like my end result to look like this (I drew this in Paint):
Any help would be appreciated!
You can make a normal plot, then play with theme to achieve the desired result.
library(ggplot2)
ggplot(data.frame(x = 1, y = 1, colour = 'Something'), aes(x, y, fill = colour))+
geom_point(alpha=0, shape = 0)+ # completely transparent rectangular point
scale_fill_manual(values='black', drop=FALSE) +
guides(fill = guide_legend(override.aes = list(alpha=1, size = 40)))+ # showing the point in the legend
theme(axis.title = element_blank(),
axis.text = element_blank(),
axis.ticks = element_blank(),
legend.position = c(0.5, 0.5), # move the legend to the center
legend.title = element_blank(),
legend.text = element_text(size = 40),
legend.key = element_rect(fill='NA'),
panel.grid = element_blank(),
panel.border = element_rect(colour = "black", fill='white', size=1)
)
Get the legend how you want it to look, then extract it with cowplot::get_legend:
library(grid)
library(cowplot)
library(ggplot2)
grid.newpage()
grid.draw(get_legend(
ggplot(data.frame(x = 1, y = 1), aes(x, y, fill = "Something")) +
geom_col(size = 20)+
scale_fill_manual(values = "white", labels = "Something", name = "") +
theme_bw() +
theme(legend.box.background = element_rect(color = "black"),
legend.title = element_text(size = 30),
legend.key.size = unit(60, "points"),
legend.text = element_text(size = 24),
legend.key = element_rect(colour = "black"),
legend.box.margin = margin(20, 20, 20, 20))))

Creating a linear gauge in R with ggplot2: reducing barplot width

I have created a linear gauge in R to be displayed within PowerBI.
My only issue is that the width of the plot cannot be adjusted so I am getting the following:
(Plot is being rendered in PowerBI)
Whereas I would like to obtain the same graph but half the width.
I tried using width within geom_bar but it resizes the bar and the final output is the same.
Ideally, the bar would be half its current width (I am building this graph for a PowerBI report).
This is the code I used:
library(ggplot2)
scores = factor(c('Inadequate','Adequate','Fair','Good','Great','Excellent','Exceptional'),
levels = (c('Inadequate','Adequate','Fair','Good','Great','Excellent','Exceptional')),
ordered = TRUE)
x <- data.frame(points = rep(1,7), scores= scores)
x %>%
ggplot(aes(x=points, fill=scores)) +
geom_bar(position = "stack", show.legend = FALSE) +
geom_text(aes(label=scores, y = seq(from=0.5, to=6.5, by = 1)), label.size = 0.25)+
coord_flip() +
theme(panel.background = element_blank(),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
axis.line = element_blank(),
axis.title = element_blank(),
axis.ticks = element_blank(),
axis.text = element_blank()) +
geom_point(aes(x= 1.45, y=5), shape = 25, size=10, colour = "black", fill = "black") +
geom_point(aes(x= 0.55, y=3), shape = 24, size=10, colour = "black", fill = "black") +
geom_point(aes(x= 0.55, y=6), shape = 24, size=10, colour = "black", fill = "black") +
scale_fill_brewer(palette = "RdYlGn", direction = -1)
If simply resizing the Power BI visual is no option, you can use theme(plot.margin = unit(c(0, 0.2, 0, 0.2), "npc")) for increasing margins that ggplot draws around plot. Full code:
library(tidyverse)
scores = factor(c('Inadequate','Adequate','Fair','Good','Great','Excellent','Exceptional'),
levels = (c('Inadequate','Adequate','Fair','Good','Great','Excellent','Exceptional')),
ordered = TRUE)
x <- data.frame(points = rep(1,7), scores= scores)
x %>%
ggplot(aes(x=points, fill=scores)) +
geom_bar(position = "stack", show.legend = FALSE) +
geom_text(aes(label=scores, y = seq(from=0.5, to=6.5, by = 1)), label.size = 0.25)+
coord_flip() +
theme(panel.background = element_blank(),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
axis.line = element_blank(),
axis.title = element_blank(),
axis.ticks = element_blank(),
axis.text = element_blank()) +
geom_point(aes(x= 1.45, y=5), shape = 25, size=10, colour = "black", fill = "black") +
geom_point(aes(x= 0.55, y=3), shape = 24, size=10, colour = "black", fill = "black") +
geom_point(aes(x= 0.55, y=6), shape = 24, size=10, colour = "black", fill = "black") +
scale_fill_brewer(palette = "RdYlGn", direction = -1) +
theme(plot.margin = unit(c(0, 0.2, 0, 0.2), "npc"))

ggplotly and geom_text vjust/hjust - how to achieve this static plot?

I've created the following plot which I'm quite pleased with when it's static - however, I wanted to make it interactive so when people hover over you can see the seasons (like pudding.cool has done here. The static plot I have:
The code to achieve this is:
character_sentiment_season_adj %>%
mutate(sent_dummy = ifelse(sentimentc < 0, "More Negative", "More Positive")) %>%
mutate(character = reorder(character, avg_sentiment)) %>%
ggplot(aes(character, sentimentc, hoverinfo = season)) +
geom_point(colour = "#666666", size = 4, fill = "#f2f2f2", shape = 21) +
coord_flip() +
geom_hline(yintercept = 0, alpha = 0.2) +
geom_point(aes(character, avg_sentiment, color=avg_sentiment), shape = 21, colour = "#262626", fill = "#ff9933", size = 4) +
geom_text(aes(label = character),
size = 3,
data = subset(character_sentiment_season_adj, sentimentc == max_sentiment),
hjust = -0.5,
vjust = 0.3) +
labs(title = "How negative are The Office (US) characters?",
subtitle = "Sentiment of each character based on bing sentiment scores") +
theme(axis.title.x = element_blank(),
axis.title.y = element_blank(),
axis.text.y = element_blank(),
axis.text.x = element_blank(),
axis.ticks = element_blank(),
axis.line = element_blank(),
panel.background = element_rect(fill = "white"),
plot.title = element_text(hjust = 0.5, face = "bold"),
plot.subtitle = element_text(hjust = 0.5),
plot.caption = element_text(size = 6)
)
However, when I turn it into a Plotly, it starts looking like this:
I've tried using style already so the code for the above plotly is:
ggplotly(p,
tooltip = "season") %>% style(textposition = "right")
I'm quite new to R. I am happy to use a package other than ggplotly if necessary.

Resources