pythonplotpython-imaging-library

Recreate plot from matplotlib using PIL


I have this data:

import numpy as np

N = 461
x = np.linspace(0, 4 * np.pi, N)
y = np.sin(x) + 50

I can plot it using matplotlib like this:

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.plot(x, y)
plt.show()

I want to recreate the drawing made in matplotlib in PIL. I have tried this:

from PIL import Image, ImageDraw

im = Image.new('L', (N, N))
draw = ImageDraw.Draw(im)
for i in range(len(x) - 1):
    draw.line((x[i], y[i], x[i+1], y[i+1]), fill='red', width=2)
im.show()

Perhaps the problem is that my data format is "4.005,4.006". How to make the same graph in PIL?


Solution

  • Your x,y values need some shifting and magnification to somewhat resemble matplotlibs plot. I am not very good in plotting. This is what I could do. You can fine tune further.

    from PIL import Image, ImageDraw
    import numpy as np
    
    N = 300
    x = np.linspace(0, 4 * np.pi, N) * 200
    y = np.sin(x) * 200 + 250
    
    im = Image.new('RGB', (500, 500), color=(255, 255, 255))
    draw = ImageDraw.Draw(im)
    for i in range(len(x) - 1):
        draw.line((x[i], y[i], x[i+1], y[i+1]), fill='red', width=1)
    im.show()