Consider the following python code block in org-mode with babel:
#+begin_src python :results none
import numpy as np
import matplotlib as mpl
from matplotlib import pyplot as plt
graylevel = 0.75
mpl.rc('figure', facecolor = (graylevel, graylevel, graylevel), edgecolor ='r')
X = np.linspace(0, 7, 1024)
plt.plot(X, np.sin(X))
plt.plot(X, np.cos(X))
plt.draw()
plt.show()
#+end_src]
In a pop-up window, this produces a plot with a gray background
but, when putting the plot in a file, again in org-mode (only the last couple of lines are different)
#+begin_src python :results file
import numpy as np
import matplotlib as mpl
from matplotlib import pyplot as plt
graylevel = 0.75
mpl.rc('figure', facecolor = (graylevel, graylevel, graylevel), edgecolor ='r')
X = np.linspace(0, 7, 1024)
plt.plot(X, np.sin(X))
plt.plot(X, np.cos(X))
plt.draw()
plt.savefig('test.png')
return 'test.png'
#+end_src
#+RESULTS:
[[file:test.png]]
The gray background is gone
I do need the gray backgrounds for exporting my plots from org-mode because I need the plots set off from the surrounding document.
I don't know if this is an issue with matplotlib, with org-mode, with python, with my machine, or with me. I hope someone can repro this example or perhaps just knows the answer.
I don't think this is an issue with org-mode, but is the same issue discussed here.
This is the solution to your troubles:
plt.savefig('test.png', facecolor=(graylevel, graylevel, graylevel))
Related
Out of pure curiosity, I would love to know why the final plt.show() does not display both plots on ax. Only the first plt.show() seems to do anything, because only the plot of y = sin(x) shows up. Here is the code sample:
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots()
x = np.linspace(1, 100, 10)
ax.plot(x, np.sin(x))
plt.show()
ax.plot(x, x)
plt.show()
Appreciate any help on this, because it bugs me to not understand why this is the case, even after a lot of searches. PS: I know that the code is useless and dumb, but I would still like to know for future use.
Your code
## load libraries
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots()
x = np.linspace(1, 100, 10)
## assign first plot
ax.plot(x, np.sin(x))
#plt.show()
## assign second plot
ax.plot(x, x)
## render the plots
plt.show()
One reason why plt.show() didn't 'show' more than once.
You are using subplots.
Your plots are on the same axes
plt.show() display all open figures. Your ax.plot(x, np.sin(x)) will be shown and the figure closed. The second is on the same ax and will not be shown anymore.
Documentation: matplotlib.pyplot.show()
[Alternate]
If however you call plt.plot() separately, (without subplots axes), you would get two plots; each with its own dimensions.
PS: below works in Jupyter (mybinder)
## load libraries
import matplotlib.pyplot as plt1
import numpy as np
x = np.linspace(1, 100, 10)
## first plot
plt1.plot(x, np.sin(x))
## render first plot
plt1.show()
Followed by
## second plot
plt1.plot(x, x)
## render the plot
plt1.show()
Clarity from the documentation: matplotlib.pyplot is a state-based interface to matplotlib
[Updated]
#JohanC lumping up the explanatory code and the alternate code.
The explanation 1, 2, and 3 remains.
The alternate code remain. or
OP can put the two plots on their own ax, and have plt.show each.
I didn't intend including this before. However, for completeness:
## load libraries
import matplotlib.pyplot as plt
import numpy as np
## tuple of desired two axes
## unpack AxesSubplot on two rows
fig, (ax1, ax2), = plt.subplots(nrows=2)
## assign variable
x = np.linspace(1, 100, 10)
## assign first plot
ax1.plot(x, np.sin(x))
#plt.show()
## assign second plot
ax2.plot(x, x)
## render the plots
## Rendering might not be 'smooth' in Jupyter
plt.show()
I am working on a code to visualize slices from a volume. I have no problem when I have to visualize only one volume as shown on the first code.
#Code working properly
import numpy as np
import matplotlib.pyplot as plt
from skimage.morphology import ball
plt.ion()
plt.show()
sphere = ball(50)
for i in range(len(sphere[0,0])):
plt.clf()
plt.title(i)
plt.imshow(sphere[:,:,i],cmap='gray')
plt.axis('off')
plt.draw()
plt.pause(0.01)
I am having trouble when I want to create a subplot and visualize more than one image simultaneously. With this code I’m able to visualize the volume but it takes too long, and it lags a lot. I have tried clearing the axes before each iteration, but I couldn’t make it work.
This is where my current attempt is at:
#Code that is not working properly
import numpy as np
import matplotlib.pyplot as plt
from skimage.morphology import ball
sphere = ball(50)
plt.ion()
plt.show()
fig, grilla = plt.subplots(1,2, figsize = (20,10))
for i in range(len(sphere[0,0])):
grilla[0].imshow(sphere[:,:,i], cmap = 'gray')
grilla[0].axis('off')
grilla[0].set_title('Slice' +str(i))
grilla[1].imshow(sphere[:,:,i], cmap = 'gray')
grilla[1].axis('off')
grilla[1].set_title('Slice' +str(i))
plt.draw()
plt.pause(0.01)
I'm really confused here; the same code in Python and in IPython Notebook produces two different PNG files with savefig:
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure(figsize=(5,4))
ax = fig.add_subplot(1,1,1)
abc = np.random.uniform(size=(50000,3))
print abc.shape
x = (2*abc[:,0]-abc[:,1]-abc[:,2])/3.0
y = (abc[:,1]-abc[:,2])/np.sqrt(3)
ax.plot(x,y,'.',markersize=0.25)
ax.set_aspect('equal')
ax.set_xlabel('x')
ax.set_ylabel('y')
with open('/tmp/screenshots/foo.png','wb') as f:
fig.savefig(f, format='png')
IPython Notebook:
Python:
It's the same PC with the same version of Python in both cases. Is there a way to get the image formatting in IPython using both methods? The Python version produces fuzzy dots and looks poor.
Argh -- I figured it out, the dpi parameter gets chosen somehow differently in the two cases, and if I force it to dpi=72 then it looks nice:
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure(figsize=(5,4))
ax = fig.add_subplot(1,1,1)
abc = np.random.uniform(size=(50000,3))
print abc.shape
x = (2*abc[:,0]-abc[:,1]-abc[:,2])/3.0
y = (abc[:,1]-abc[:,2])/np.sqrt(3)
ax.plot(x,y,'.',markersize=0.25)
ax.set_aspect('equal')
ax.set_xlabel('x')
ax.set_ylabel('y')
with open('/tmp/screenshots/foo.png','wb') as f:
fig.savefig(f, format='png', dpi=72)
I would like to use a ColorFunction similar to that in Mathematica for my plots in python.
In other words, I would like to call pyplot.plot(x, y, color=c), where c is a vector, defining the color of each data point.
Is there any way to achieve this using the matplotlib library?
To the best of my knowledge, there is no equivalent in Matplotlib, but we can get the similar result following two steps: draw points with varied colors and draw the line.
Here is a demo.
The source code,
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import cm
import random
fig, ax = plt.subplots()
nrof_points = 100
x = np.linspace(0, 10, nrof_points)
y = np.sin(x)
colors = cm.rainbow(np.linspace(0, 1, nrof_points)) # generate a bunch of colors
# draw points
for idx, point in enumerate(zip(x, y)):
ax.plot(point[0], point[1], 'o', color=colors[idx], markersize=10)
# draw the line
ax.plot(x, y, 'k')
plt.grid()
plt.show()
While I agree with #SparkAndShine that there is no way to parameterize the color of one line, it is possible to color many lines to create a visual effect that is largely the same. This is at the heart of a demo in the MatPlotLib documentation. However, this demo is not the simplest implementation of this principle. Here is an alternate demo based on #SparkAndShine's response:
colored sine (can't post as image since I don't have the reputation)
Source code:
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import cm
fig, ax = plt.subplots()
nrof_points = 100
x = np.linspace(0, 10, nrof_points)
y = np.sin(x)
colors = cm.rainbow(np.linspace(0, 1, nrof_points)) # generate a bunch of colors
# draw points
for idx in range(0,np.shape(x)[0]-2,1):
ax.plot(x[idx:idx+1+1], y[idx:idx+1+1], color=colors[idx])
# add a grid and show
plt.grid()
plt.show()
I have a problem when making graphs using matplotlib,
for some simple graphs the library works fine, for example:
import matplotlib.pyplot as plt
plt.plot([1,2,3,4])
plt.ylabel('some numbers')
plt.show()
but when I use figure module, i get blank figures, like this
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots()
x = np.linspace(0, 10, 200)
y = np.sin(x)
ax.plot(x, y, 'r-', linewidth=2, label=r'$y=\sin(x)$', alpha=0.6)
ax.legend(loc='upper center')
plt.show()
I've tried the same code in a a different python editor or using the shell and it woks fine. I'm using :
Windows,
PyDev v4.2,
python v2.7.10