scipy: savefig without frames, axes, only content
EDIT
Changed aspect='normal
to aspect='auto'
since that changed in more recent versions of matplotlib (thanks to @Luke19).
Assuming :
import matplotlib.pyplot as plt
To make a figure without the frame :
fig = plt.figure(frameon=False)
fig.set_size_inches(w,h)
To make the content fill the whole figure
ax = plt.Axes(fig, [0., 0., 1., 1.])
ax.set_axis_off()
fig.add_axes(ax)
Then draw your image on it :
ax.imshow(your_image, aspect='auto')
fig.savefig(fname, dpi)
The aspect
parameter changes the pixel size to make sure they fill the figure size specified in fig.set_size_inches(…)
. To get a feel of how to play with this sort of things, read through matplotlib's documentation, particularly on the subject of Axes, Axis and Artist.
Save an image (only content, without axes or anything else) to a file using Matloptlib
I think you want subplots_adjust
:
fig,ax = plt.subplots(1)
fig.subplots_adjust(left=0,right=1,bottom=0,top=1)
ax.axis('tight')
ax.axis('off')
In this case:
import matplotlib.pyplot as plt
from scipy.io import wavfile
import numpy as np
def graph_spectrogram(wav_file):
rate, data = wavfile.read(wav_file)
fig,ax = plt.subplots(1)
fig.subplots_adjust(left=0,right=1,bottom=0,top=1)
ax.axis('off')
pxx, freqs, bins, im = ax.specgram(x=data, Fs=rate, noverlap=384, NFFT=512)
ax.axis('off')
fig.savefig('sp_xyz.png', dpi=300, frameon='false')
if __name__ == '__main__': # Main function
graph_spectrogram('...')
How to save a figure without the borders/margins in matplotlib.pyplot?
I got help somewhere else and these borders/margins are called spines.
They are deleted in the following way, in my case:
ax.spines['right'].set_visible(False)
ax.spines['left'].set_visible(False)
ax.spines['top'].set_visible(False)
ax.spines['bottom'].set_visible(False)
matplotlib create figure without frames, axes, plot a 2D array with a colormap, save plot to numpy array of same size as input
If you're wanting RGB output that exactly matches the shape of the input array, it's probably easiest to not create a figure, and instead use the colormap objects directly. For example:
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
# Random data with a non 0-1 range.
data = 500 * np.random.random((100, 100)) - 200
# We'll use `LinearSegementedColormap` and `Normalize` instances directly
cmap = plt.get_cmap('viridis')
norm = plt.Normalize(data.min(), data.max())
# The norm instance scales data to a 0-1 range, cmap makes it RGB
rgb = cmap(norm(data))
# MPL uses a 0-1 float RGB representation, so we'll scale to 0-255
rgb = (255 * rgb).astype(np.uint8)
Image.fromarray(rgb).save('test.png')
Note that you likely don't want the additional step of saving it as a PNG, but I wanted to be able to show the result visually. This is exactly a 100x100 image where each pixel corresponds to the original input data.
This is what matplotlib does behind-the-scenes when you call imshow. The data is first run through a Normalize
instance to scale it from its original range to 0-1. Then any Colormap
instance can be called directly with the 0-1 results to turn the scalar data into RGB data.
Cannot save graph made in Networkx and matplotlib
Adding bbox_inches='tight'
while saving solved the problem:
plt.savefig('save.png',bbox_inches='tight')
This argument cuts unnecessary whitespace margins around output image. Without it only some part of whole figure is saved.
Valuable discussion about how to save pure image in matplotlib is here:
scipy: savefig without frames, axes, only content
You can find the bbox of the image inside the axis (using
get_window_extent), and use the bbox_inches parameter to save only
that portion of the image
Dendrogram axes not saved by savefig
Removing this line
ax = fig.add_axes([0.1,0.1,0.75,0.75])
and setting bbox_inches='tight'
in plt.savefig()
makes it work for me.
Also, since you are loading the data with pandas, note how you can declare the 'name' column as index and use these index values as labels.
from matplotlib import pyplot as plt
from scipy.cluster.hierarchy import dendrogram, linkage
import numpy as np
import pandas as pd
data = pd.read_csv('input.txt', header=0, index_col=['name'], sep="\t")
data = data.fillna(0)
link_matrix = linkage(data, 'ward')
fig, ax = plt.subplots(1, 1, figsize=(20,200))
ax.set_title('Hierarchical Clustering Dendrogram')
ax.set_xlabel('distance')
ax.set_ylabel('name')
dendrogram(
link_matrix,
orientation='left',
leaf_rotation=0.,
leaf_font_size=12.,
labels=data.index.values
)
ax.yaxis.set_label_position('right')
ax.yaxis.tick_right()
plt.savefig('plt1.png', dpi=320, format='png', bbox_inches='tight')
Matplotlib Savefig Function Draws Axes Over Self if Transparent is True
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure(1) # This is as persistent as assigning to whatever function
def init_axes(fig):
fig.clear()
return dict(
t_ax = plt.subplot2grid((6,2),(1,0)),
t_fit_ax = plt.subplot2grid((6,2),(1,1)),
o_ax = plt.subplot2grid((6,2),(2,0)),
o_fit_ax = plt.subplot2grid((6,2),(2,1)),
table = plt.subplot2grid((6,2),(3,0),
rowspan = 3, colspan = 2)
)
#A function which makes figures using the single figure
def Disp(i=5):
pi = 3.141592653589793
xs = np.linspace(-pi/2,pi/2)
for n in range(i):
axes = init_axes(fig)
for name,ax in axes.items():
ax.plot(xs,np.sin(xs*n))
fig.savefig('bad'+str(n),transparent=True)
fig.savefig('good'+str(n),transparent=False)
Related Topics
Imports in _Init_.Py and 'Import As' Statement
What Is the Correct Way to Set Python's Locale on Windows
Why Is the Global Keyword Not Required in This Case
Function Name Is Undefined in Python Class
How to Load Existing Db File to Memory in Python SQLite3
How to Use Inspect to Get the Caller's Info from Callee in Python
How to Set Default Python Version to Python3 in Ubuntu
Run Child Processes as Different User from a Long Running Python Process
Implement Matlab's Im2Col 'Sliding' in Python
Django Submit Two Different Forms with One Submit Button
Why Do "Not a Number" Values Equal True When Cast as Boolean in Python/Numpy
Easy Pretty Printing of Floats
Removing Duplicates from Dictionary
Difference Between Returns and Printing in Python
How to Include Related Model Fields Using Django Rest Framework
How to Use Jupyter Notebooks in a Conda Environment