Hello,
This is how I usually export a chart/plot from ggplot() into a .png file. I am not sure this is a good way but it works pretty well for me so far
> plot_pie = pie(slices,labels = lbls, col = c("red","green","blue"),
+ main = "Sales Dollars Percentage Distribution", cex=0.8)
> plot_pie
NULL
> ggsave('Sales Percentage Comparison.png', plot_pie, width = 15, height = 10, dpi = 300)
Of course, this does not export anything because:
> plot_pie
NULL
I don't need to post any data because this is mainly a coding issue.
How can I tackle this?
Thanks!
cderv
June 30, 2018, 3:38pm
2
I am not sure but I think ggsave
can be used only for a ggplot graph and pie
is not - it is a function for base R.
For regular plot, you can use grDevices::png()
for png graphic devices
png('Sales Percentage Comparison.png', width = 15, height = 10, units = "in")
pie(slices,labels = lbls, col = c("red","green","blue"), main = "Sales Dollars Percentage Distribution", cex=0.8)
dev.off()
I thing this should work; You may have to tweak it though.
EDIT:
I just checked. pie
is not like a ggplot function, it does not return an object. So you can use ggsave
but by directly providing the plot call.
temp_file <- tempfile(fileext = ".png")
ggplot2::ggsave(
filename = temp_file,
plot = pie(rep(1, 24), col = rainbow(24), radius = 0.9),
width = 15,
height = 10,
dpi = 300
)
img <- magick::image_read(temp_file)
magick::image_scale(img, 'x300')
unlink(temp_file)
Created on 2018-06-30 by the reprex package (v0.2.0).
2 Likes
cderv:
png('Sales Percentage Comparison.png', width = 15, height = 10, units = "in") pie(slices,labels = lbls, col = c("red","green","blue"), main = "Sales Dollars Percentage Distribution", cex=0.8) dev.off()
> pie(slices,labels = lbls, col = c("red","green","blue"), main = "Sales Dollars Percentage Distribution", cex=0.8)
> png('Sales Percentage Comparison.png', width = 15, height = 10, units = "in")
Error in .geometry(width, height, units, res) :
'res' must be specified unless 'units = "px"'
Solution:
ggsave('Sales Percentage Comparison.png', pie(slices,labels = lbls, col = c("red","green","blue"), main = "Sales Dollars Percentage Distribution", cex=0.8)
+ , width = 15, height = 10, dpi = 300)
cderv
June 30, 2018, 8:33pm
5
Yes. As in the example I provided, it works that way with ggsave
but required ggplot2.
For the other solution, just change the units for width and length or provide a res
argument as explained in the error message.
1 Like