Save panda boxplot as image
Asked Answered
M

2

8

I'm trying to save a pandas.DataFrame.boxplot variable to a image to use it with a Qt widget, but I don't know how to convert this variable. I have this code:

import matplotlib.pyplot as plt
from pandas import DataFrame
import numpy as np


df = DataFrame(np.random.rand(10,5))
plt.figure();
bp = df.boxplot()

And Spyder shows it:

Are there instructions to do it automatically within the code?

Motheaten answered 29/5, 2017 at 14:12 Comment(0)
D
3

Are you looking for a standard image format?

If so this will do the trick:

import matplotlib.pyplot as plt
plt.savefig()

docs: https://matplotlib.org/devdocs/api/_as_gen/matplotlib.pyplot.savefig.html

Defilade answered 29/5, 2017 at 14:18 Comment(0)
H
5

Suppose you have multiple figures and you want to save them independently when you want in the code: make sure you can access it by a unique name:

fig100 = figure()        
outputBoxplot100 = df_100.boxplot(column=['1', '2', '4', '5', '8'])
plt.title("100 MHz")
fig150 = figure()
outputBoxplot150 = df_150.boxplot(column=['1', '2', '4', '5', '8'])
plt.title("150 MHz")

# do other stuff

fig100.savefig("test100.svg", format="svg")
fig150.savefig("test150.svg", format="svg")

In this case, I would change your code in:

import matplotlib.pyplot as plt
from pandas import DataFrame
import numpy as np


df = DataFrame(np.random.rand(10,5))
myFig = plt.figure();
bp = df.boxplot()
myFig.savefig("myName.svg", format="svg")

The result will be a saved file named "myName.svg":

enter image description here

Please note: I am using svg but you can use the format you like the most ( png, jpeg, etc) that this micro supports. Check on the availability on Pandas website.

Hall answered 7/3, 2019 at 13:56 Comment(2)
I am getting an empty figure with this. It shows on Jupiter Notebook, but the saved .png file is a blank figure. Any thoughts? Edit: if I copy and paste your code it works, but when doing my own dataset it saves an empty figure even thought it shows me the boxplots just as I expected! I tried .svg as wellSharpeyed
@Jonathan, copy and paste a minimal amount of code to reproduce your error and ask a completely new question :) Remember: a few lines of code to reproduce your error. It is possible that, during this little homework effort, you can find the solution yourself :)Hall
D
3

Are you looking for a standard image format?

If so this will do the trick:

import matplotlib.pyplot as plt
plt.savefig()

docs: https://matplotlib.org/devdocs/api/_as_gen/matplotlib.pyplot.savefig.html

Defilade answered 29/5, 2017 at 14:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.