I’m having trouble exporting plots in ggplot. I want to display my data using different variables in different plots and have the plot panel size export to the same size every time. My issue is that sometimes my legends are wider or shorter and R ends up smushing my plot to accommodate for the size of the legend. I want the plot panel to print in the same dimensions every time, and for R to stretch the width of the image it exports to accommodate the varying sizes of legends.
library(ggplot2)
my_data <- data.frame(
Name = c("Alice Smith", "Eduardo Fernandez", "Steven Brown"),
Age = c(25, 30, 22),
Gender = c("Female", "Male", "Male"),
Height = c(165, 180, 175))
p1 <- ggplot(data = my_data, aes(x = Age, y = Height, color = Gender))+
geom_point(size = 2, stroke = 1)
p1
ggsave(filename = "p1.png",
plot = p1,
device = "png",
height = 7,
width = 10,
units = "in",
dpi = 500,
bg="black")
dev.off()
p2 <- ggplot(data = my_data, aes(x = Age, y = Height, color = Gender,shape=Name))+
geom_point(size = 2, stroke = 1)
p2
ggsave(filename = "p2.png",
plot = p2,
device = "png",
height = 7,
width = 10,
units = "in",
dpi = 500,
bg="black")
dev.off()
I know that technically you can do this by making your export width wider or smaller and checking every single time to make sure that the panel is the same size but it’s so time consuming. I have been painstakingly exporting the plots .2 inches wider at a time and checking to see if the panels are exactly the same until I get it right. There must be a better way.