If I execute the following code, the resulting eps-file does not contain tick labels or axes labels.
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0,2*np.pi,100)
y = np.sin(x)
plt.figure()
plt.plot(x,y)
plt.xlabel('x')
plt.ylabel('sin(x)')
plt.savefig('image.eps', format='eps')
As some additional information: I am using version 4.3.0 of the anaconda distribution and execute my code in Spyder 3.1..2. I tested the two backends TkAgg and Qt5Agg, the result is the same for both.
Any ideas how I can get a correct eps-file?
Alternatively: which other vector graphics format could I use if I want to import into MS Word later?
So I think that you will find your answer here: https://stackoverflow.com/a/20817722/2402281
It might be the case that your matplotlib backend does not support that operation. You can change the matplotlib backend as follows:
# The default backend; one of GTK GTKAgg GTKCairo GTK3Agg GTK3Cairo
# CocoaAgg MacOSX Qt4Agg Qt5Agg TkAgg WX WXAgg Agg Cairo GDK PS PDF SVG
import matplotlib
matplotlib.use('PS')
or in the matplotlibrc (see the documentation).
I encountered same question. The eps file is fine when I plot time series or scatter plot. But when I am plotting geospatial plots using dataframe data, the saved eps file contain no texts and tick labels. So I simply tried:
import matplotlib
matplotlib.use('PS')
matplotlib.rcParams['text.usetex'] = True
It seems that if you turn the text.usetex to True, it may help.
Btw, my Matplotlib is 3.4.2, and operation system is MacOS, and I am using Spyder with python 3.7. Actually I don't know why it sometimes works sometimes does not work, and why it works after I adding matplotlib.rcParams['text.usetex'] = True...It may be because I used alpha when I plot the geospatial plots (like set alpha=5 in ax.scatter). I will put some tiny examples later.
Related
I am using ipython-notebook a lot at the moment for numerical analysis and plotting of data. In the process of preparing publication quality plots there is a lot of tweaking to get the layout just right, however I can't get ipython/matplotlib to show me what I will be saving in the browser. Making the process more painful than it should be because I have to keep opening the new output file to check it.
Is there a way to get the image that is displayed inline to be the same as the image that is saved?
Example as follows, facecolor='gray' for clarity:
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
fig = plt.figure(figsize=(6,4),facecolor='gray')
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])
x = np.linspace(0,2*np.pi,1000)
y = np.sin(x)
ax.plot(x,y,label=r'$\sin(x)$')
ax.set_xlim(0,2*np.pi)
ax.set_ylim(-1.2,1.2)
ax.set_xlabel(r'$x$')
ax.set_ylabel(r'$y$')
ax.legend(loc='upper right', frameon=False)
fig.savefig('mypath.png',dpi=300, facecolor='gray')
plt.show()
Note here I have explicity chosen my axes dimensions so that they are equidistant from the two sides of the resulting image. This is respected in the saved image, but ignored in the image shown in the notebook:
Notebook displayed image:
Savefig image:
As noted by #andrew, the ipython magics are enforcing bbox_inches='tight' by default. This can be overridden using other magics as explained in the ipython documentation:
%matplotlib inline
%config InlineBackend.print_figure_kwargs = {'bbox_inches':None}
produces an inline image identical to that produced by savefig.
The behavior is due to the fact that the magic %matplotlib inline defaults to using the
bbox_inches='tight' when rendering inline.
I know you asked about changing the behavior of plt.show(), but alternatively, you could change the behavior of savefig() to use the same settings as the notbeook.
fig.savefig('mypath.png',dpi=300, facecolor='gray', bbox_inches='tight')
New 'savefig' image:
I am trying to plot a couple of line graphs using Matplotlib and the small dashes which marks the center of the xticks are not showing up. Here is a sample plot I found online which has the marks (I circled them).
Now below is my code and the graph. I know it's not related to spines.
Code:
from sklearn.externals import joblib
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import seaborn as sns
import math
sns.set()
sns.set_style("dark")
sns.set_style("white")
plt.figure()
plt.plot([1,2,3,4,5],[10,5,69,38,52],label='test')
plt.xticks([1,2,3,4,5],['apple','orange','grapes','lemon','pear'],ha='right')
plt.xticks(rotation=45)
plt.savefig("test.png", dpi=300)
OS: MacOX High Sierra 10.13, Python: 3.6.0 and no Virtual Environments
You can customise the seaborn styles to add back ticks (there is also a style for ticks). See here for the full details.
Just change your set_style line to have a second parameter which is a dictionary of overrides. In this case it is setting the size of the xticks. That link gives the full details of built-in styles and all the options for overriding.
sns.set_style("white", {"xtick.major.size": 5})
I am using ipython-notebook a lot at the moment for numerical analysis and plotting of data. In the process of preparing publication quality plots there is a lot of tweaking to get the layout just right, however I can't get ipython/matplotlib to show me what I will be saving in the browser. Making the process more painful than it should be because I have to keep opening the new output file to check it.
Is there a way to get the image that is displayed inline to be the same as the image that is saved?
Example as follows, facecolor='gray' for clarity:
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
fig = plt.figure(figsize=(6,4),facecolor='gray')
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])
x = np.linspace(0,2*np.pi,1000)
y = np.sin(x)
ax.plot(x,y,label=r'$\sin(x)$')
ax.set_xlim(0,2*np.pi)
ax.set_ylim(-1.2,1.2)
ax.set_xlabel(r'$x$')
ax.set_ylabel(r'$y$')
ax.legend(loc='upper right', frameon=False)
fig.savefig('mypath.png',dpi=300, facecolor='gray')
plt.show()
Note here I have explicity chosen my axes dimensions so that they are equidistant from the two sides of the resulting image. This is respected in the saved image, but ignored in the image shown in the notebook:
Notebook displayed image:
Savefig image:
As noted by #andrew, the ipython magics are enforcing bbox_inches='tight' by default. This can be overridden using other magics as explained in the ipython documentation:
%matplotlib inline
%config InlineBackend.print_figure_kwargs = {'bbox_inches':None}
produces an inline image identical to that produced by savefig.
The behavior is due to the fact that the magic %matplotlib inline defaults to using the
bbox_inches='tight' when rendering inline.
I know you asked about changing the behavior of plt.show(), but alternatively, you could change the behavior of savefig() to use the same settings as the notbeook.
fig.savefig('mypath.png',dpi=300, facecolor='gray', bbox_inches='tight')
New 'savefig' image:
Hello I am using the Ubuntu Server 14.04 LTS (HVM), SSD Volume Type instance from amazon aws and I am running python 2.7.9 and the latest version of matplotlib. I am trying to plot the sine function and then save the figure to a png in the home directory. Below is my code:
import matplotlib
matplotlib.use('AGG')
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0,2*np.pi,100)
y = np.sin(x)
plt.plot(x,y)
plt.savefig('Sine')
after I save the figure I use WinSCP to move the png file to my local desktop so that I can open it. But when I open the file I only see the black box with x and y tick marks.
Am I just using the wrong backend, or is the problem egregiously more severe?
I believe your problem comes from the fact that you are actually plotting nothing to your plot because x is empty. The step you use is too large in your np.arange. The third argument to np.arange is the step or increment use to build the array, unlike matlab linspace function, for which the third argument is the number of points generated.
Try this instead:
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0,2*np.pi,0.01)
y = np.sin(x)
plt.plot(x,y)
plt.savefig('Sine.png')
which results in this png (in Ubuntu 15.04, Python 2.7.9, matplotlib 1.4.2):
update(2015-07-28):
Regarding the backend, as suggested in the pyplot documentation:
If format is None and fname is a string, the output format is deduced from the extension of the filename. If the filename has no extension, the value of the rc parameter savefig.format is used.
If fname is not a string, remember to specify format to ensure that the correct backend is used.
So maybe to explicitly specifying an extension to the file will help solving the issue regarding the backend (I've updated the code accordingly). By default, the backend TkAgg is used on my machine, so there was no problem plotting with the default settings.
I'm trying to use matplotlib to generate 3D figures where the xy plane is an image, and then some 3D tracks are drawn on top (that part works just fine). The problem is, even though my imported PNG shows just fine with imshow, and even though I can plot an image on a 3D axis if I just use an example from the cookbook, my image just shows up as a featureless black box. I'm sure I'm missing something small- thanks in advance!
import matplotlib as mpl
from mpl_toolkits.mplot3d import Axes3D, art3d
from pylab import ogrid
import matplotlib.pyplot as plt
plt.ioff()
fig = plt.figure()
ay=fig.add_subplot(2,1,1)
rawim=plt.imread(r'G:\Path\myimage.png')
ay.imshow(rawim,cmap='gray')
ax=fig.add_subplot(2,1,2,projection='3d')
x,y= ogrid[0:rawim.shape[0],0:rawim.shape[1]]
ax.plot_surface(x,y,0,rstride=5,cstride=5,facecolors=rawim,cmap='gray')
ax.view_init(elev=45, azim=12)
plt.show()
The output comes out as this (edited to include image).
PS Running Matplotlib 1.2.1 in Spyder for Python 2.75
Edited to add- I was largely modeling my approach from this post, so if instead of
rawim=plt.imread(r'G:\Path\myimage.png')
I use
from matplotlib.cbook import get_sample_data
fn = get_sample_data("lena.png", asfileobj=False)
rawim=read_png(fn)
it works perfectly. I've tried several of my PNG outputs, produced a couple of different ways, and no love. And yes, they're greyscale between 0-1.
You should use an explicit color array for facecolors.
You want something having shape (Nx, Ny, 4) where the "4" dimension holds RGBA values.
Also, get rid of the cmap='gray' in the plot_surface invocation.