I am using ggplot2 to plot a picture in my server, now I want to transfer the picture to front-end. In fact, the front-end can send some plot commands to the server, so after generating the png, the server need to transfer it to front-end. My current method is to save the png as tempory png, and delete it as soon as it has been transfered. Like this:
def r_function(x,y,filename):
r_code = f"""
library(ggplot2)
p <- ggplot(data.frame(x={x}, y={y}), aes(x=x, y=y)) +
geom_point() +
labs(title="R Plot")
ggsave(p, filename="{filename}", width=4, height=3, dpi=300)
"""
robjects.r(r_code)
def test(request):
x = request.GET.get("x", "c(1,2,3,4,5)")
y = request.GET.get("y", "c(2,4,6,8,10)")
filename = f"{uuid.uuid4()}_plot.png"
with conversion.localconverter(default_converter):
r_function(x, y, filename)
with open(f"{filename}", "rb") as f:
response = HttpResponse(f.read(), content_type="image/png")
response["Content-Disposition"] = f"inline; filename={filename}"
# delete the temporay file
os.remove(filename)
return response
But I think this soultion is not efficent, I don't hope generate the tempory file and i just want to transfer the png file once it has been generated. So is there any better way to solve the problem?