Exporting SVG files from plots created in Python - python

So I'm trying to export some plots I created using matplotlib and seaborn.
I create my plot with:
import pandas as pd
import matplotlib as plt
import matplotlib.pyplot as plt
from matplotlib import pyplot as plty
import seaborn as sns
%matplotlib inline
from IPython.display import set_matplotlib_formats
set_matplotlib_formats('png', 'pdf')
df = pd.read_excel('test.xlsx', sheetname='IvT')
sns.set_style("white")
plt.figure(figsize=(12,10))
plt.xlabel('Test', fontsize=18)
plt.title ('Test', fontsize=22)
#sns.boxplot(df[['Short total']])
sns.boxplot(df[['Short total']])
plt.show()
If I try to export it with
matplotlib.pyplot.savefig("test.svg", format="svg")
I get an error message saying
--------------------------------------------------------------------------- NameError Traceback (most recent call
last) in ()
1
----> 2 matplotlib.pyplot.savefig("test.svg", format="svg")
NameError: name 'matplotlib' is not defined

You seem to be overcomplicating the importing of modules. In the code, you have imported matplotlib and matplotlib.pyplot as plt. In addition, having already imported matplotlib.pyplot, you try and do it again using from matplotlib import pyplot
When you try and save your file you have then done matplotlib.pyplot.savefig, but you have already imported matplotlib.pyplot as plt.
The specific error you have shown is because, while you have import matplotlib itself, you have imported it as plt, which is why the error says that matplotlib is not defined.
In order to fix this, you need to clean up the imports like so:
import pandas as pd
import matplotlib # if abbreviating this, use "as mpl"
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
from IPython.display import set_matplotlib_formats
set_matplotlib_formats('png', 'pdf')
df = pd.read_excel('test.xlsx', sheetname='IvT')
sns.set_style("white")
plt.figure(figsize=(12,10))
plt.xlabel('Test', fontsize=18)
plt.title ('Test', fontsize=22)
#sns.boxplot(df[['Short total']])
sns.boxplot(df[['Short total']])
plt.show()
Then in order to save your figure use:
plt.savefig("test.svg", format="svg")
Remember to call this before plt.show()

Related

Matplotlib, prevent plot from showing

df_rm_count[['count']].sort_values(by='count', ascending=False).plot.barh()
The above line shows the graph (without plt.show())
I'd like to save the plot as image but can't because plot immediately displays the plot
I tried
%matplotlib (to negate %matplotlib inline I get ModuleNotFoundError: No module named '_tkinter' error)
plt.ioff()
plt.close('all')
matplotlib.pyplot.close(fig)
matplotlib.interactive(False)
none of the above worked..
edit
Agg didn't work either..
import matplotlib as mpl
mpl.use('Agg')
ipykernel_launcher.py:2: UserWarning: This call to matplotlib.use() has no effect because the backend has already been chosen; matplotlib.use() must be called
*before* pylab, matplotlib.pyplot, or matplotlib.backends is imported for the first time.
You can use a different backend that cannot display a figure, for example Agg
import matplotlib as mpl
mpl.use('Agg')
In order to not restart the kernel, put plt.switch_backend('Agg') right below the lines that create fig and ax, for example
fig = plt.figure(figsize=(8, 8))
ax = fig.add_subplot(111)
plt.switch_backend('Agg')
df = pd.DataFrame()
df['a'] = [1,2,3]
df['a'].plot.barh(ax=ax)

Matplotlib FuncAnimation not plotting any chart inside Jupyter Notebook

Simple matplotlib plot. Here is my code
from matplotlib import pyplot as plt
from matplotlib.animation import FuncAnimation
from itertools import count
import random
x = []
y = []
index=count()
def animate(i):
x.append(next(index))
y.append(random.randint(0,10))
plt.plot(x,y)
a = FuncAnimation(plt.gcf(),animate,interval=1000)
plt.tight_layout()
plt.show()
Running the code above I get
<Figure size 576x396 with 0 Axes>
but no chart appears.
Are you using Jupyter notebooks to run it? I tried with native libraries and it works just fine. The plots are visible.
Checking here i see the same situation. Could you try to use %matplotlib inline before importing matplotlib as:
%matplotlib inline # this line before importing matplotlib
from matplotlib import pyplot as plt
That said, the animation can be displayed using JavaScript. This is similar to the ani.to_html5() solution, except that it does not require any video codecs.
from IPython.display import HTML
HTML(a.to_jshtml())
this answer brings a more complete overview...

Using Matplotlib for plotting 3D data - warning/error importing module [duplicate]

When using the typical 3D plot like so:
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.gca(projection='3d')
flake8 reports the expected error:
./tools.py:62:9: F401 'mpl_toolkits.mplot3d.Axes3D' imported but unused
I know it can be avoided using the # NOQA comment. But is there a different way to formulate the projection in the figure so that the Axes3D object is used?
If this is only about actually using the import at least once, you can do
ax = fig.gca(projection=Axes3D.name)
as "3d" is the name of the Axes3D class by which it is registered to the projection list.
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
fig = plt.figure()
ax = Axes3D(fig)
However, if I understand the documentation well, it is not the preferred way anymore since version 1.0.0. I still mention it for completeness.

How to directly use Axes3D from matplotlib in standard plot to avoid flake8 error

When using the typical 3D plot like so:
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.gca(projection='3d')
flake8 reports the expected error:
./tools.py:62:9: F401 'mpl_toolkits.mplot3d.Axes3D' imported but unused
I know it can be avoided using the # NOQA comment. But is there a different way to formulate the projection in the figure so that the Axes3D object is used?
If this is only about actually using the import at least once, you can do
ax = fig.gca(projection=Axes3D.name)
as "3d" is the name of the Axes3D class by which it is registered to the projection list.
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
fig = plt.figure()
ax = Axes3D(fig)
However, if I understand the documentation well, it is not the preferred way anymore since version 1.0.0. I still mention it for completeness.

Python "'module' object is not callable"

I'm trying to make a plot:
from matplotlib import *
import sys
from pylab import *
f = figure ( figsize =(7,7) )
But I get this error when I try to execute it:
File "mratio.py", line 24, in <module>
f = figure( figsize=(7,7) )
TypeError: 'module' object is not callable
I have run a similar script before, and I think I've imported all the relevant modules.
The figure is a module provided by matplotlib.
You can read more about it in the Matplotlib documentation
I think what you want is matplotlib.figure.Figure (the class, rather than the module)
It's documented here
from matplotlib import *
import sys
from pylab import *
f = figure.Figure( figsize =(7,7) )
or
from matplotlib import figure
f = figure.Figure( figsize =(7,7) )
or
from matplotlib.figure import Figure
f = Figure( figsize =(7,7) )
or to get pylab to work without conflicting with matplotlib:
from matplotlib import *
import sys
import pylab as pl
f = pl.figure( figsize =(7,7) )
You need to do:
matplotlib.figure.Figure
Here,
matplotlib.figure is a package (module), and `Figure` is the method
Reference here.
So you would have to call it like this:
f = figure.Figure(figsize=(7,7))
To prevent future errors regarding matplotlib.pyplot, try doing this:
import matplotlib.pyplot as plt
If you use Jupyter notebooks and use: %matplotlib inline, make sure that the "%matplotlib inline FOLLOWS the import matplotlib.pyplot as plt
Karthikr's answer works but might not eliminate errors in other lines of code related to the pyplot module.
Happy coding!!
Instead of
from matplotlib import *
use
import matplotlib.pyplot as plt
For Jupyter notebook I solved this issue by importig matplotlib.pyplot instead.
import matplotlib.pyplot as plt
%matplotlib notebook
Making plots with f = plt.figure() now works.
Wrong Library:
import matplotlib as plt
plt.figure(figsize=(7, 7))
TypeError: 'module' object is not callable
But
Correct Library:
import matplotlib.pyplot as plt
plt.figure(figsize=(7, 7))
Above code worked for me for the same error.

Categories