Generating a Png With Matplotlib When Display Is Undefined

Generating a PNG with matplotlib when DISPLAY is undefined

The main problem is that (on your system) matplotlib chooses an x-using backend by default. I just had the same problem on one of my servers. The solution for me was to add the following code in a place that gets read before any other pylab/matplotlib/pyplot import:

import matplotlib
# Force matplotlib to not use any Xwindows backend.
matplotlib.use('Agg')

The alternative is to set it in your .matplotlibrc

create png without show figure

take off the "plt." and it will work

from matplotlib.pyplot import *
time = [0, 1, 2, 3]
position = [0, 100, 200, 300]
plot(time, position)
xlabel('Time (hr)')
ylabel('Position (km)')

Matplotlib plot not appearing on saved png image

Just change the places of savefig and show methods. The problem will be solved.

import numpy as np
import matplotlib.pyplot as plt
import time
import random
import math

''' 0<theta<pi/2 si v0<30 '''
#global constant variables#
scale = 1
g = -9.8#m/s^2
dt = 0.01 #heavy performance impact !(timestep>0)
t = 0#s
#input
initialvelocity = scale*float(input("initial velocity : "))
theta = float(input("theta : "))
#initial conditions#
#speed_vector_decomposition
initialxvel = initialvelocity*math.cos(math.radians(theta))
initialyvel = initialvelocity*math.sin(math.radians(theta))
initialxpos = 0
initialypos = 0
xpos = initialxpos
ypos = initialypos
xposlist = []
yposlist = []
while ypos>=0:
t+=dt
xpos = initialxvel*t
ypos = initialyvel*t+1/2*g*t*t
xposlist.append(xpos)
yposlist.append(ypos)
plt.plot(xposlist, yposlist)
plt.grid(True)
plt.xlabel('x (m) ')
plt.ylabel('y (m) ')
plt.title('2d motion')
plt.xlim(0, 100)
plt.ylim(0, 100)

#plt.plot([0, 1000], [0, 1000])
plt.savefig('test.png')
plt.show()

Output:

Sample Image

make matplotlib png plot semi-transparent with non integer alpha value

Your code behaved correctly and nothing is wrong. I tried it on colab and here is the results (notice the ax.patch.set_alpha() value):

import matplotlib.pyplot as plt
import numpy as np

fig,ax=plt.subplots()
ax.plot ([1,2,3],[2,1,3])
ax.patch.set_facecolor('white')
ax.patch.set_alpha(1)
plt.savefig('test.png', facecolor=fig.get_facecolor(), edgecolor='none')

Sample Image

import matplotlib.pyplot as plt
import numpy as np

fig,ax=plt.subplots()
ax.plot ([1,2,3],[2,1,3])
ax.patch.set_facecolor('white')
ax.patch.set_alpha(0)
plt.savefig('test.png', facecolor=fig.get_facecolor(), edgecolor='none')

Sample Image

Updated:
After saving the plot, you can load it with opencv then change its transparency like this:

"""
pip install opencv-python
"""
import cv2

im = cv2.imread('test.png',cv2.IMREAD_UNCHANGED)
im[:,:,3] = im[:,:,3]/2
cv2.imwrite('adjust.png',im)

Update 2:
I think I found what you want:

import matplotlib.pyplot as plt
import numpy as np
import cv2

fig,ax=plt.subplots()
ax.plot ([1,2,3],[2,1,3])
ax.patch.set_facecolor('white')
plt.savefig('original.png', edgecolor='none')
plt.savefig('transparent.png', edgecolor='none',transparent=True)
#Then
im = cv2.imread('original.png',cv2.IMREAD_UNCHANGED)
im[:,:,3] = im[:,:,3]/2 + 120
cv2.imwrite('semi_transparent.png',im)

Here is the results I got (tested on MS word):

Sample Image

Generating matplotlib graphs without a running X server

@Neil's answer is one (perfectly valid!) way of doing it, but you can also simply call matplotlib.use('Agg') before importing matplotlib.pyplot, and then continue as normal.

E.g.

import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(range(10))
fig.savefig('temp.png')

You don't have to use the Agg backend, as well. The pdf, ps, svg, agg, cairo, and gdk backends can all be used without an X-server. However, only the Agg backend will be built by default (I think?), so there's a good chance that the other backends may not be enabled on your particular install.

Alternately, you can just set the backend parameter in your .matplotlibrc file to automatically have matplotlib.pyplot use the given renderer.

generating a JPG with matplotlib with UTF-8 labels when DISPLAY is undefined in python

I think you just have to specify a usable font:

# -*- coding: utf-8 -*-

import matplotlib
matplotlib.use('Agg')
import matplotlib.pylab as plt

plt.plot(range(10))
# you might need to change this to be a font that you know works for your gylphs
# that you have installed
plt.xlabel(u'وَبَوِّئْنا', name='Arial')

plt.savefig('test.jpg',format='jpg')

Sample Image

You can modify the font.serif and font.sans-serif fields is rcparam to change the default font search order to put a font that has the glyphs first.



Related Topics



Leave a reply



Submit