Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib stores .svg different than what is show on screen

Here is an example. The next is what get's stored as a .png and this is how it displays on the screen and it is correct

this is the image that looks right

and the next is the .svg which is using interpolation for the heatmap

enter image description here

They are both stored using the next line of code respectively

plt.savefig(filename,format='png')
plt.savefig(filename,format='svg')

And the next is the code that generates the actual plot

def heatmapText(data,xlabels=[],ylabels=[],cmap='jet',fontsize=7):
    '''
    Heatmap with text on each of the cells
    '''


    plt.imshow(data,interpolation='none',cmap=cmap)

    for y in range(data.shape[0]):
        for x in range(data.shape[1]):
            plt.text(x , y , '%.1f' % data[y, x],
                     horizontalalignment='center',
                     verticalalignment='center',
                     fontsize=fontsize
                     )

    plt.gca()
    if ylabels!=[]:
        plt.yticks(range(ylabels.size),ylabels.tolist(),rotation='horizontal')
    if xlabels!=[]:
        plt.xticks(range(xlabels.size),xlabels.tolist(),rotation='vertical')

For both plots I used exactly the same function but stored it in different formats. Last, in screen appears correctly (like in the .png).

Any ideas on how to have the .svg to store the file correctly?

like image 430
Juli Avatar asked Sep 03 '25 06:09

Juli


1 Answers

Based on http://matplotlib.org/examples/images_contours_and_fields/interpolation_none_vs_nearest.html

What does matplotlib `imshow(interpolation='nearest')` do?

and

matplotlib shows different figure than saves from the show() window

I'm going to recommend trying this with interpolation=nearest

The following code gives me identical displayed and saved as svg plots:

import matplotlib.pyplot as plt
import numpy as np

A = np.random.rand(5, 5)
plt.figure(1)
plt.imshow(A, interpolation='nearest')

plt.savefig('fig',format='svg')
plt.show()
like image 57
Ianhi Avatar answered Sep 04 '25 21:09

Ianhi