I have the same file saved both as .pdf and as .svg
I'd like to insert the file in a regular matplotlib plot.
How can I do that?
import matplotlib.pyplot as plt
pdfFile = open('file.pdf')
svgFile = open('file.svg')
fig,ax = plt.subplots(1,2)
ax[0].imshow(pdfFile)
ax[1].imshoe(svgFile)
plt.show()
Alternately I've tried with
from svglib.svglib
import svg2rlg
from reportlab.graphics import renderPDF, renderPM >>> >>> drawing = svg2rlg("file.svg") >>> renderPDF.drawToFile(drawing, "file.pdf")
Related
I would like imshow display current image pixel value in hex format, by default it display pixel with decimal format.
for example, red color will be displayed as (255,0,0), I would like it to be (FF,00,00).
#!/usr/bin/env python3
import matplotlib.pyplot as plt
import matplotlib.image as image
import matplotlib.patches as patches
import matplotlib
import cv2
matplotlib.use('tkagg')
img = cv2.imread("input.png",cv2.IMREAD_UNCHANGED)# cv2.IMREAD_UNCHANGED load alpha channel
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
fig,ax =plt.subplots(1,figsize=(15,15))
ax.imshow(img)
fig.tight_layout()
plt.show()
You could connect a function the motion_notify_event and update the toolbar. Here is a standalone example:
import matplotlib.pyplot as plt
import matplotlib.cbook as cbook
import matplotlib
def show_hex_coords(event):
text = ''
rgb = img_plot.get_cursor_data(event)
if rgb is not None:
r, g, b = rgb
text = f'x={event.xdata:.0f} y={event.ydata:.0f}\n{r:02X} {g:02X} {b:02X}'
# print( f'#{r:02X}{g:02X}{b:02X}')
fig.canvas.toolbar.set_message(text)
matplotlib.use('tkagg')
with cbook.get_sample_data('grace_hopper.jpg') as image_file:
img = plt.imread(image_file)
fig, ax = plt.subplots(1, figsize=(6, 6))
img_plot = ax.imshow(img)
fig.canvas.mpl_connect("motion_notify_event", show_hex_coords)
plt.show()
Below code is taken from http://www.acgeospatial.co.uk/sentinel-5p-and-python/
This is a very nice tutorial on how to process with Sentinel 5p netCDF data.
Now I tried to save obtained plt image as georeferenced Tiff (geoTiff). How to do this?
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
from netCDF4 import Dataset
import numpy as np
file = 'S5P_OFFL_L2__O3_____20201025T093552_20201025T111721_15720_01_020103_20201027T030032.nc'
fh = Dataset(file, mode='r')
lons = fh.groups['PRODUCT'].variables['longitude'][:][0,:,:]
lats = fh.groups['PRODUCT'].variables['latitude'][:][0,:,:]
o3 = fh.groups['PRODUCT'].variables['ozone_total_vertical_column'][0,:,:]
o3_units = fh.groups['PRODUCT'].variables['ozone_total_vertical_column_precision'].units
#o3_units = o3_units
m = Basemap(width=5000000,height=3500000,\
llcrnrlon=-15.,llcrnrlat=30.,urcrnrlon=80.,urcrnrlat=80.,\
resolution='c',projection='merc',\
#lat_ts=40,lat_0=lat_0,lon_0=lon_0)
lat_ts=40,lat_0=50,lon_0=20)
xi, yi = m(lons, lats)
# Plot Data
cs = m.pcolor(xi,yi,np.squeeze(o3*2241.15), cmap='jet')
#plt.axis('off')
plt.show()
As you see the result is presented with plt.show metod. But I would like to save it to geoTiff. Thanks!
I am trying to show a gif file in google's colab.research. I was able to save the file in the directory with the following path name /content/BrowniamMotion.gif but I don't know how to show this GIF in my notebook to present.
The code to generate the GIF so far, in case someone can manipulate it not to save the GIF but rather to animate it directly into the google colab file was,
# Other Brownian Motion
from math import *
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits import mplot3d
import matplotlib.animation as animation
fig = plt.figure(figsize=(8,6))
ax = plt.axes(projection='3d')
N=10
#val1 = 500
x=500*np.random.random(N)
y=500*np.random.random(N)
z=500*np.random.random(N)
def frame(w):
ax.clear()
global x,y,z
x=x+np.random.normal(loc=0.0,scale=50.0,size=10)
y=y+np.random.normal(loc=0.0,scale=50.0,size=10)
z=z+np.random.normal(loc=0.0,scale=50.0,size=10)
plt.title("Brownian Motion")
ax.set_xlabel('X(t)')
ax.set_xlim3d(-500.0,500.0)
ax.set_ylabel('Y(t)')
ax.set_ylim3d(-500.0,500.0)
ax.set_zlabel('Z(t)')
ax.set_zlim3d(-500.0,500.0)
plot=ax.scatter
3D(x, y, z, c='r')
return plot
anim = animation.FuncAnimation(fig, frame, frames=100, blit=False, repeat=True)
anim.save('BrowniamMotion.gif', writer = "pillow", fps=10 )
Sorry if this question is badly, stated. I am new to Python and using colab research.
For Colab it is easiest to use 'jshtml' to display matplotlib animation.
You need to set it up with
from matplotlib import rc
rc('animation', html='jshtml')
Then, just type your animation object. It will display itself
anim
Here's a workable colab of your code.
It has a slider where you can run back and forth at any point in time.
Using the same authors git repository seems like we have a solution to embed the plots as GIFs ( Save Matplotlib Animations as GIFs ).
#!apt install ffmpeg
#!brew install imagemagick
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from matplotlib import animation, rc
from IPython.display import HTML, Image # For GIF
rc('animation', html='html5')
np.random.seed(5)
# Set up formatting for the movie files
Writer = animation.writers['ffmpeg']
writer = Writer(fps=15, metadata=dict(artist='Me'), bitrate=1800)
def generateRandomLines(dt, N):
dX = np.sqrt(dt) * np.random.randn(1, N)
X = np.cumsum(dX, axis=1)
dY = np.sqrt(dt) * np.random.randn(1, N)
Y = np.cumsum(dY, axis=1)
lineData = np.vstack((X, Y))
return lineData
# Returns Line2D objects
def updateLines(num, dataLines, lines):
for u, v in zip(lines, dataLines):
u.set_data(v[0:2, :num])
return lines
N = 501 # Number of points
T = 1.0
dt = T/(N-1)
fig, ax = plt.subplots()
data = [generateRandomLines(dt, N)]
ax = plt.axes(xlim=(-2.0, 2.0), ylim=(-2.0, 2.0))
ax.set_xlabel('X(t)')
ax.set_ylabel('Y(t)')
ax.set_title('2D Discretized Brownian Paths')
## Create a list of line2D objects
lines = [ax.plot(dat[0, 0:1], dat[1, 0:1])[0] for dat in data]
## Create the animation object
anim = animation.FuncAnimation(fig, updateLines, N+1, fargs=(data, lines), interval=30, repeat=True, blit=False)
plt.tight_layout()
plt.show()
# Save as GIF
anim.save('animationBrownianMotion2d.gif', writer='pillow', fps=60)
Image(url='animationBrownianMotion2d.gif')
## Uncomment to save the animation
#anim.save('brownian2d_1path.mp4', writer=writer)
Check this link out on using the HTML to get it to work http://louistiao.me/posts/notebooks/embedding-matplotlib-animations-in-jupyter-notebooks/ .
I didn't embed a link but instead imbedded a HTML video that got it to work.
# Other Brownian Motion
from math import *
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits import mplot3d
import matplotlib.animation as animation
from IPython.display import HTML
fig = plt.figure(figsize=(8,6))
ax = plt.axes(projection='3d')
N=10
val1 = 600
x=val1*np.random.random(N)
y=val1*np.random.random(N)
z=val1*np.random.random(N)
def frame(w):
ax.clear()
global x,y,z
x=x+np.random.normal(loc=0.0,scale=50.0,size=10)
y=y+np.random.normal(loc=0.0,scale=50.0,size=10)
z=z+np.random.normal(loc=0.0,scale=50.0,size=10)
plt.title("Brownian Motion")
ax.set_xlabel('X(t)')
ax.set_xlim3d(-val1,val1)
ax.set_ylabel('Y(t)')
ax.set_ylim3d(-val1,val1)
ax.set_zlabel('Z(t)')
ax.set_zlim3d(-val1,val1)
plot=ax.scatter3D(x, y, z, c='r')
return plot
anim = animation.FuncAnimation(fig, frame, frames=100, blit=False, repeat=True)
anim.save('BrowniamMotion.gif', writer = "pillow", fps=10 )
HTML(anim.to_html5_video())
Essentially all we did hear was add,
from IPython.display import HTML to the premable and then add the line HTML(anim.to_html5_video()). This code then produces a video and saves the gif.
import numpy as np
import os.path
from skimage.io import imread
from skimage import data_dir
img = imread(os.path.join(data_dir, 'checker_bilevel.png'))
import matplotlib.pyplot as plt
#plt.imshow(img, cmap='Blues')
#plt.show()
imgT = img.T
plt.figure(1)
plt.imshow(imgT,cmap='Greys')
#plt.show()
imgR = img.reshape(20,5)
plt.figure(2)
plt.imshow(imgR,cmap='Blues')
plt.show(1)
I read that plt.figure() will create or assign the image a new ID if not explicitly given one. So here, I have given the two figures, ID 1 & 2 respectively. Now I wish to see only one one of the image.
I tried plt.show(1) epecting ONLY the first image will be displayed but both of them are.
What should I write to get only one?
plt.clf() will clear the figure
import matplotlib.pyplot as plt
plt.plot(range(10), 'r')
plt.clf()
plt.plot(range(12), 'g--')
plt.show()
plt.show will show all the figures created. The argument you forces the figure to be shown in a non-blocking way. If you only want to show a particular figure you can write a wrapper function.
import matplotlib.pyplot as plt
figures = [plt.subplots() for i in range(5)]
def show(figNum, figures):
if plt.fignum_exists(figNum):
fig = [f[0] for f in figures if f[0].number == figNum][0]
fig.show()
else:
print('figure not found')
I want to generate a vector plot with matplotlib. I tried hard - but the output is a raster image. Here's what I use:
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
and finally:
myfig.savefig('myfig.eps', format='eps')
I've found that export to ps gives a vector image, but the problem with eps remains.
I use the following code:
from matplotlib import pyplot as plt
fig, ax = plt.subplots() # or
fig.savefig('filename.eps', format='eps')
If you need emf files as output format, e.g. to insert high quality plots into ms word/powerpoint and you are willing to use inkscape as converter you can apply this solution:
from matplotlib import pyplot as plt
import subprocess, os
def plot_as_emf(figure, **kwargs):
inkscape_path = kwargs.get('inkscape', "C://Program Files//Inkscape//inkscape.exe")
filepath = kwargs.get('filename', None)
if filepath is not None:
path, filename = os.path.split(filepath)
filename, extension = os.path.splitext(filename)
svg_filepath = os.path.join(path, filename+'.svg')
emf_filepath = os.path.join(path, filename+'.emf')
figure.savefig(svg_filepath, format='svg')
subprocess.call([inkscape_path, svg_filepath, '--export-emf', emf_filepath])
os.remove(svg_filepath)
In order to test this function you can run a simple example:
plt.plot([1,2], [4,5])
fig = plt.gcf()
plot_as_emf(fig, filename="C:/test.emf")
Can try for svg format:
plt.savefig("filepath.svg", format = 'svg', dpi=300)
Try exporting as a pdf or svg as described in http://neuroscience.telenczuk.pl/?p=331
If you need an eps the pdf2ps command works great.