Can't display patches with mplleaflet - python-3.x

I'm trying to display a circle of fixed size in a leaflet map.
I tried with .add_artist()(see here) and I'm now trying with .add_patch()
import mplleaflet
import matplotlib.pyplot as plt
import matplotlib as mpl
fig, ax = plt.subplots()
x = 2.363561
y = 48.951918
r = 20
circle1 = mpl.patches.Circle((x,y), radius=r)
circle2= plt.Circle((x, y), r, color='r')
#ax.add_patch(circle1)
#ax.add_patch(circle2)
mplleaflet.show(fig=ax.figure)
You can try to uncomment one of the two commented lines, it doesn't matter which line is uncommented, same error pops.
Here is the trace I get :
Traceback (most recent call last):
File "<ipython-input-81-1fdd7f4a9d12>", line 16, in <module>
mplleaflet.show(fig = ax.figure)
File "C:\ProgramData\Anaconda3\lib\site-packages\mplleaflet\_display.py", line 180, in show
save_html(fig, fileobj=f, **kwargs)
File "C:\ProgramData\Anaconda3\lib\site-packages\mplleaflet\_display.py", line 131, in save_html
html = fig_to_html(fig, **kwargs)
File "C:\ProgramData\Anaconda3\lib\site-packages\mplleaflet\_display.py", line 84, in fig_to_html
exporter.run(fig)
File "C:\ProgramData\Anaconda3\lib\site-packages\mplleaflet\mplexporter\exporter.py", line 51, in run
self.crawl_fig(fig)
File "C:\ProgramData\Anaconda3\lib\site-packages\mplleaflet\mplexporter\exporter.py", line 118, in crawl_fig
self.crawl_ax(ax)
File "C:\ProgramData\Anaconda3\lib\site-packages\mplleaflet\mplexporter\exporter.py", line 138, in crawl_ax
self.draw_patch(ax, patch)
File "C:\ProgramData\Anaconda3\lib\site-packages\mplleaflet\mplexporter\exporter.py", line 227, in draw_patch
mplobj=patch)
File "C:\ProgramData\Anaconda3\lib\site-packages\mplleaflet\leaflet_renderer.py", line 125, in draw_path
rings = list(iter_rings(data, pathcodes))
File "C:\ProgramData\Anaconda3\lib\site-packages\mplleaflet\utils.py", line 14, in iter_rings
raise ValueError('Unrecognized code: {}'.format(code))
ValueError: Unrecognized code: C
Any idea on how to solve this ?
===========================
EDIT :
Just to see what would happen, I tried doing the same thing than this, which is changing
elif code == 'L': ring.append(point)
to
elif code == 'L' or code == 'Z' or code == 'S' or code == 'C': ring.append(point)
in mplleaflet\utils.py, line 11 and 12. Here is what I got :
===========================
EDIT 2 to answer comment
mpl.patches.Rectangle and plt.Rectangle show up :
rect1 = mpl.patches.Rectangle((x,y), 1, 1, color = 'r')
rect2 = plt.Rectangle((x, y), 1, 1, fc='r')
Which seems to fit with a rectangle of 1 degree in latitude and 1 degree longitude (see here) (maybe ? Seems a bit small).
As for Polygons, well... At least they show up, but I guess there is a projection problem :
regpol1 = mpl.patches.RegularPolygon((x,y), 100, radius=r, color = 'r')
cirpol1 = mpl.patches.CirclePolygon((x +50,y), radius=r, color = 'b')

Related

mplcursors crash on setting "annotation_positions"

I found some issue, maybe a bug in mplcursors library. Because already done the reproducable code, put this below:
import matplotlib.pyplot as plt
import mplcursors
import numpy as np
import pandas as pd
N = 30
n = [int(i) for i in range(0,N)]
x = np.random.random(N)*10
y = np.random.random(N)*10
z = np.random.random(N)*10
df = pd.DataFrame(data = np.array([n, x, y, z]).T, columns = ['id', 'X', 'Y', 'Z'])
fig = plt.figure(frameon=False, facecolor='yellow', edgecolor='green', dpi=200, figsize=(8,5))
ax = fig.gca(projection='3d')
points = ax.scatter3D(x, y, z, s=5, marker='o', edgecolor='black', linewidth=.5)
def getInfo(sel):
n,x,y,z = df.loc[sel, ['id', 'X', 'Y', 'Z']]
row = "Point: " + str(n) + "\n" + str(x) + ", \n" + str(y) + ", \n" + str(z)
return row
ap = [{'horizontalalignment': 'left', 'verticalalignment': 'top', 'anncoords': 'offset points'}] #, 'position': (8, -8)}]
mc = mplcursors.cursor(points, hover=2, annotation_positions=ap)
mc.connect("add", lambda sel: sel.annotation.set_text( getInfo(sel.index) ))
mc.connect("add", lambda sel: sel.annotation.get_bbox_patch().set(fc="palegreen", alpha=0.75))
plt.show()
The error message is here:
Traceback (most recent call last):
File "C:\Users\cp\Anaconda3\lib\site-packages\matplotlib\cbook\__init__.py", line 196, in process
func(*args, **kwargs)
File "C:\Users\cp\Anaconda3\lib\site-packages\mplcursors\_mplcursors.py", line 567, in _on_hover_motion_notify
self._on_select_event(event)
File "C:\Users\cp\Anaconda3\lib\site-packages\mplcursors\_mplcursors.py", line 615, in _on_select_event
self.add_selection(pi)
File "C:\Users\cp\Anaconda3\lib\site-packages\mplcursors\_mplcursors.py", line 412, in add_selection
bbox = ann.get_window_extent(renderer)
File "C:\Users\cp\Anaconda3\lib\site-packages\matplotlib\text.py", line 2403, in get_window_extent
bboxes.append(self.arrow_patch.get_window_extent())
File "C:\Users\cp\Anaconda3\lib\site-packages\matplotlib\patches.py", line 609, in get_window_extent
return self.get_path().get_extents(self.get_transform())
File "C:\Users\cp\Anaconda3\lib\site-packages\matplotlib\patches.py", line 4218, in get_path
_path, fillable = self.get_path_in_displaycoord()
File "C:\Users\cp\Anaconda3\lib\site-packages\matplotlib\patches.py", line 4238, in get_path_in_displaycoord
shrinkB=self.shrinkB * dpi_cor
File "C:\Users\cp\Anaconda3\lib\site-packages\matplotlib\patches.py", line 2775, in __call__
clipped_path = self._clip(path, patchA, patchB)
File "C:\Users\cp\Anaconda3\lib\site-packages\matplotlib\patches.py", line 2728, in _clip
left, right = split_path_inout(path, insideA)
File "C:\Users\cp\Anaconda3\lib\site-packages\matplotlib\cbook\deprecation.py", line 296, in wrapper
return func(*args, **kwargs)
File "C:\Users\cp\Anaconda3\lib\site-packages\matplotlib\bezier.py", line 274, in split_path_inout
ctl_points, command = next(path_iter)
StopIteration
The issue is in the line:
ap = [{'horizontalalignment': 'left', 'verticalalignment': 'top',
'anncoords': 'offset points'}] #, 'position': (8, -8)}]
Everything works if I either skip the ap variable, or add position variable to the list. No other way round. The drawback for this is that I can't justify the text without ap and the position of hover is not selecting automatically - when the ap is assigned.
If anyone knows the solution to have justification without manually positioning the hoverbox please answer, however it's minor issue at the end.

I tried running code for my SLAMTECH RPlidar but the lidar doesnt get imported in my python window but it show it has been imported on my terminal

Here is the error
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/matplotlib/cbook/__init__.py", line 224, in process
func(*args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/matplotlib/animation.py", line 959, in _start
self._init_draw()
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/matplotlib/animation.py", line 1703, in _init_draw
self._draw_frame(next(self.new_frame_seq()))
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/matplotlib/animation.py", line 1726, in _draw_frame
self._drawn_artists = self._func(framedata, *self._args)
File "/Users/lkhagvabyambajav/Desktop/rplidar/examples/animate.py", line 14, in update_line
scan = next(iterator)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/rplidar.py", line 357, in iter_scans
for new_scan, quality, angle, distance in iterator:
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/rplidar.py", line 323, in iter_measurments
raw = self._read_response(dsize)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/rplidar.py", line 199, in _read_response
raise RPLidarException('Wrong body size')
rplidar.RPLidarException: Wrong body size
and code is
from rplidar import RPLidar
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.animation as animation
PORT_NAME = '/dev/tty.usbserial-0001'
DMAX = 4000
IMIN = 0
IMAX = 50
def update_line(num, iterator, line):
scan = next(iterator)
offsets = np.array([(np.radians(meas[1]), meas[2]) for meas in scan])
line.set_offsets(offsets)
intens = np.array([meas[0] for meas in scan])
line.set_array(intens)
return line,
def run():
lidar = RPLidar(PORT_NAME)
fig = plt.figure()
ax = plt.subplot(111, projection='polar')
line = ax.scatter([0, 0], [0, 0], s=5, c=[IMIN, IMAX],
cmap=plt.cm.Greys_r, lw=0)
ax.set_rmax(DMAX)
ax.grid(True)
iterator = lidar.iter_scans()
ani = animation.FuncAnimation(fig, update_line,
fargs=(iterator, line), interval=50)
plt.show()
lidar.stop()
lidar.disconnect()
if __name__ == '__main__':
run()
I didnt write this code it is from https://github.com/SkoltechRobotics/rplidar
Im trying to test my lidar to see if it is working.
Any help will be appreciated. Many thanks :)
i'm using python 2.7 and Lidar A1M8 ('hardware': 7, 'model': 24, 'firmware': (1, 29)) to run it and it works with no errors.
So i think you should take a look at the RPlidar library and the lidar version which is supported, i've seen an issue about that constraint. Try to use another library like pylidar2.
there is the issue : https://github.com/SkoltechRobotics/rplidar/issues/36#issuecomment-787215840,
take a look at https://github.com/Roboticia/RPLidar

'TypeError: 'NoneType' object is not iterable' during running of opencv/kivy/python code

Okay for last 2 weeks or so I have been teaching myself both opencv and kivy in order to create a UI/Camera System for Autonomous mission from MATE ROV. (I don't feel like explaining about MATE ROV just google it) I have succeeded in creating both the UI and the camera implementation. However, whenever I go to add the cv2.HoughLinesP calculation to find the length of a rectangle in my test image.
[Test Image][1]
I get created by the code running for a short amount of time (usually runs through entire code a couple of times) then I get this.
Traceback (most recent call last):
File "main.py", line 87, in <module>
CamApp().run()
File "/home/mlees/kivy_venv/lib/python3.6/site-packages/kivy/app.py", line 855, in run
runTouchApp()
File "/home/mlees/kivy_venv/lib/python3.6/site-packages/kivy/base.py", line 504, in runTouchApp
EventLoop.window.mainloop()
File "/home/mlees/kivy_venv/lib/python3.6/site-packages/kivy/core/window/window_sdl2.py", line 747, in mainloop
self._mainloop()
File "/home/mlees/kivy_venv/lib/python3.6/site-packages/kivy/core/window/window_sdl2.py", line 479, in _mainloop
EventLoop.idle()
File "/home/mlees/kivy_venv/lib/python3.6/site-packages/kivy/base.py", line 339, in idle
Clock.tick()
File "/home/mlees/kivy_venv/lib/python3.6/site-packages/kivy/clock.py", line 591, in tick
self._process_events()
File "kivy/_clock.pyx", line 384, in kivy._clock.CyClockBase._process_events
File "kivy/_clock.pyx", line 414, in kivy._clock.CyClockBase._process_events
File "kivy/_clock.pyx", line 412, in kivy._clock.CyClockBase._process_events
File "kivy/_clock.pyx", line 167, in kivy._clock.ClockEvent.tick
File "main.py", line 56, in update
for line in buf8:
TypeError: 'NoneType' object is not iterable
I have no clue what is causing this error so if anyone can help me out that would be great. Full Code is below.
from kivy.uix.widget import Widget
from kivy.uix.gridlayout import GridLayout
from kivy.uix.image import Image
from kivy.uix.label import Label
from kivy.clock import Clock
from kivy.graphics.texture import Texture
import cv2
import numpy as np
class CamApp(App):
def build(self):
self.img0 = Image()
self.img1 = Image()
self.img2 = Image()
self.img3 = Image()
layout = GridLayout(cols = 4, rows = 3)
layout.add_widget(self.img0)
layout.add_widget(self.img1)
layout.add_widget(Label(text="HELP"))
layout.add_widget(Label(text="HELP"))
layout.add_widget(self.img2)
layout.add_widget(self.img3)
layout.add_widget(Label(text="HELP"))
layout.add_widget(Label(text="HELP"))
layout.add_widget(Label(text="HELP"))
layout.add_widget(Label(text="HELP"))
layout.add_widget(Label(text="HELP"))
layout.add_widget(Label(text="HELP"))
#opencv2 stuffs
self.capture = cv2.VideoCapture(0)
Clock.schedule_interval(self.update, 1.0/33.0)
return layout
def update(self, dt):
# display image from cam in opencv window
ret, frame = self.capture.read()
# Flip Image and set up first frame
buf1 = cv2.flip(frame, -1)
# Convert main frame to Grayscale
buf3 = cv2.cvtColor(buf1, cv2.COLOR_BGR2GRAY)
# Take Grayscale and add an adaptiveThreshold
buf5 = cv2.adaptiveThreshold(buf3,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY,11,2)
# Edge detection and line detection
buf7 = cv2.Canny(buf3,80,240,3)
buf8 = cv2.HoughLinesP(buf7, 1, np.pi/180, 60, np.array([]), 50, 5)
for line in buf8:
for x1, y1, x2, y2 in line:
cv2.line(buf8, (x1, y1), (x2, y2), (255, 255, 255), 4)
distance_pixels = np.sqrt(np.square(x2 - x1) + np.square(y2 - y1))
print(distance_pixels)
# Necessary to display all the transformations and other bullshit
buf0 = buf1.tostring()
buf2 = buf3.tostring()
buf4 = buf5.tostring()
buf6 = buf7.tostring()
# The next 9 lines are kivy bullshit to get the images on the screen.
texture0 = Texture.create(size=(frame.shape[1], frame.shape[0]), colorfmt='bgr')
texture1 = Texture.create(size=(frame.shape[1], frame.shape[0]), colorfmt='luminance')
texture2 = Texture.create(size=(frame.shape[1], frame.shape[0]), colorfmt='luminance')
texture3 = Texture.create(size=(frame.shape[1], frame.shape[0]), colorfmt='luminance')
texture0.blit_buffer(buf0, colorfmt='bgr', bufferfmt='ubyte')
texture1.blit_buffer(buf2, colorfmt='luminance', bufferfmt='ubyte')
texture2.blit_buffer(buf4, colorfmt='luminance', bufferfmt='ubyte')
texture3.blit_buffer(buf6, colorfmt='luminance', bufferfmt='ubyte')
# display image from the texture
self.img0.texture = texture0
self.img1.texture = texture1
self.img2.texture = texture2
self.img3.texture = texture3
# Here's the running shit.
if __name__ == '__main__':
CamApp().run()
cv2.destroyAllWindows()
Thanks in advance!
This error is arising because in some case, no line is found by HoughLinesP() function thus "buf8" have value "None" at those instances.
Add a line before starting the for loop to check if "buf8" is "None" or not. If not None process, else break the process.

"ValueError: 'c' argument has 28 elements, which is not acceptable for use with 'x' with size 33, 'y' with size 33" with Networkx k-partite graph

I am getting the following errors when I am trying to apply different colors to the different node-sets or Ks in my k-partite graph.
G = nx.Graph()
G.add_nodes_from(emc["entity"], bipartite=0)
G.add_nodes_from(set(EMM_unique["keys"]).symmetric_difference(set(emc["entity"])), bipartite=1)
G.add_nodes_from(EMM["id"], bipartite=2)
G.add_edges_from(list(emc.itertuples(index=False)), color='red')
G.add_edges_from(list(EMM.itertuples(index=False)))
nodes = G.nodes()
# for each of the parts create a set
nodes_0 = set([n for n in nodes if G.nodes[n]['bipartite']==0])
nodes_1 = set([n for n in nodes if G.nodes[n]['bipartite']==1])
nodes_2 = set([n for n in nodes if G.nodes[n]['bipartite']==2])
# set the location of the nodes for each set
pos = dict()
pos.update( (n, (1, i)) for i, n in enumerate(nodes_0) ) # put nodes from X at x=1
pos.update( (n, (2, i)) for i, n in enumerate(nodes_1) ) # put nodes from Y at x=2
pos.update( (n, (3, i)) for i, n in enumerate(nodes_2) ) # put nodes from X at x=1
# To apply colors to different node-sets
color_map = []
for node in G:
if node in emc["entity"].values:
print(node)
color_map.append('red')
elif node in EMM["id"].values:
color_map.append('green')
#nx.draw_networkx_nodes(G,pos, node_color=color_map)
nx.draw(G, pos, node_color=color_map, width= 2, with_labels=True, with_arrows=True)
plt.show()
If I don't use color_map code then it runs fine. With color_map code I am getting the following error message
Traceback (most recent call last):
File "C:\Python\lib\site-packages\matplotlib\axes\_axes.py", line 4291, in _parse_scatter_color_args
raise ValueError
ValueError
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "C:\Program Files\JetBrains\PyCharm 2019.2.5\helpers\pydev\_pydev_bundle\pydev_umd.py", line 197, in runfile
pydev_imports.execfile(filename, global_vars, local_vars) # execute the script
File "C:\Program Files\JetBrains\PyCharm 2019.2.5\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
exec(compile(contents+"\n", file, 'exec'), glob, loc)
File "C:/Users/Pawandeep/Desktop/CVS1/dev/AnnotationBexis.py", line 287, in <module>
nx.draw(G, pos, node_color=color_map, width= 2, with_labels=True, with_arrows=True)
File "C:\Python\lib\site-packages\networkx\drawing\nx_pylab.py", line 128, in draw
draw_networkx(G, pos=pos, ax=ax, **kwds)
File "C:\Python\lib\site-packages\networkx\drawing\nx_pylab.py", line 279, in draw_networkx
node_collection = draw_networkx_nodes(G, pos, **kwds)
File "C:\Python\lib\site-packages\networkx\drawing\nx_pylab.py", line 416, in draw_networkx_nodes
label=label)
File "C:\Python\lib\site-packages\matplotlib\__init__.py", line 1601, in inner
return func(ax, *map(sanitize_sequence, args), **kwargs)
File "C:\Python\lib\site-packages\matplotlib\axes\_axes.py", line 4454, in scatter
get_next_color_func=self._get_patches_for_fill.get_next_color)
File "C:\Python\lib\site-packages\matplotlib\axes\_axes.py", line 4298, in _parse_scatter_color_args
.format(nc=n_elem, xs=xsize, ys=ysize)
ValueError: 'c' argument has 28 elements, which is not acceptable for use with 'x' with size 33, 'y' with size 33.
I have already tried adding the nodes separately with the color through this code but getting the similar error
nx.draw_networkx_nodes(G,pos, node_color=color_map)
My requirement is to have different colors for different node-set. It would be very helpful if I can get some assistance with that.
Solution:
As per the suggestion from the accepted answer, I have added condition for all three node sets so now
for node in G:
if node in emc["entity"].values:
color_map.append("red")
elif node in EMM["id"].values:
color_map.append("green")
else:
color_map.append("blue") # solution
In these lines:
color_map = []
for node in G:
if node in emc["entity"].values:
print(node)
color_map.append('red')
elif node in EMM["id"].values:
color_map.append('green')
you assign a color to a node only if it is in emc["entity"].values or EMM["id"].values. I think you have some nodes that are in neither. So when you try to draw it, the list of nodes is longer than the list of colors.
Anytime you use an elif you need to allow for the possibility that there are some things that satisfy neither condition. Otherwise you should use else.

matplotlib is now giving an 'Unknown property' AttributeError since update to Python 3:

I am using astroplan to set up some astronomical observations. Previously, when I ran my code using Python 2.7, it plotted the target on the sky properly. Now, I have moved to Python 3.7 and I get an AttributError on the same code.
I took my larger code and stripped out everything that did not seem to trigger the error. Here below is code that will generate the complaint.
from astroplan import Observer, FixedTarget
import astropy.units as u
from astropy.time import Time
import matplotlib.pyplot as plt
from astroplan.plots import plot_sky
import numpy as np
time = Time('2015-06-16 12:00:00')
subaru = Observer.at_site('subaru')
vega = FixedTarget.from_name('Vega')
sunset_tonight = subaru.sun_set_time(time, which='nearest')
vega_rise = subaru.target_rise_time(time, vega) + 5*u.minute
start = np.max([sunset_tonight, vega_rise])
plot_sky(vega, subaru, start)
plt.show()
Expected result was a simple plot of the target, in this case, the star Vega, on the sky as seen by the Subaru telescope in Hawaii. The astroplan docs give a tutorial that shows how it was to look at the very end of this page:
https://astroplan.readthedocs.io/en/latest/tutorials/summer_triangle.html
Instead, I now get the following error:
Traceback (most recent call last):
File "plot_sky.py", line 16, in <module>
plot_sky(vega, subaru, start)
File "/usr1/local/anaconda_py3/ana37/lib/python3.7/site-packages/astropy/utils/decorators.py", line 842, in plot_sky
func = make_function_with_signature(func, name=name, **wrapped_args)
File "/usr1/local/anaconda_py3/ana37/lib/python3.7/site-packages/astropy/units/decorators.py", line 222, in wrapper
return_ = wrapped_function(*func_args, **func_kwargs)
File "/local/data/fugussd/rkbarry/.local/lib/python3.7/site-packages/astroplan/plots/sky.py", line 216, in plot_sky
ax.set_thetagrids(range(0, 360, 45), theta_labels, frac=1.2)
File "/usr1/local/anaconda_py3/ana37/lib/python3.7/site-packages/matplotlib/projections/polar.py", line 1268, in set_thetagrids
t.update(kwargs)
File "/usr1/local/anaconda_py3/ana37/lib/python3.7/site-packages/matplotlib/text.py", line 187, in update
super().update(kwargs)
File "/usr1/local/anaconda_py3/ana37/lib/python3.7/site-packages/matplotlib/artist.py", line 916, in update
ret = [_update_property(self, k, v) for k, v in props.items()]
File "/usr1/local/anaconda_py3/ana37/lib/python3.7/site-packages/matplotlib/artist.py", line 916, in <listcomp>
ret = [_update_property(self, k, v) for k, v in props.items()]
File "/usr1/local/anaconda_py3/ana37/lib/python3.7/site-packages/matplotlib/artist.py", line 912, in _update_property
raise AttributeError('Unknown property %s' % k)
AttributeError: Unknown property frac

Resources