Tqdm status bar for generating a Folium map - python

I am generating a map inside Google Colab using the Folium python library and would like to show a progress bar as the code is working on spitting out a map rendering.
I'm fairly new to programming, but I gather that tqdm can generate a status bar over an iterable. I don't necessarily have an iterable built into my code, but I'm wondering how to 'wrap' my code in a tqdm function to show a status bar as I wait for the various !pip install, import, and folium functions to run. Unfortunately, Colab forces me to run the !pip install statements each time in order to work properly.
Here is my code for generating a fairly simple map, although the status bar doesn't behave as expected:
for i in tqdm(range(1), desc = 'Generating Map'):
!pip install geopandas &> /dev/null
!pip install branca &> /dev/null
import folium
from folium.plugins import HeatMap
from folium.features import GeoJsonTooltip
import geopandas as gpd
import pandas as pd
import os
from branca.element import Figure
import glob
from google.colab import drive
m=folium.Map(location=[40.43912857098136, -79.94770150049476],tiles=None)
folium.TileLayer(
tiles = 'https://mt1.google.com/vt/lyrs=m&x={x}&y={y}&z={z}',
attr = 'Google',
name = 'Google Maps',
overlay = False,
control = True,
zoom_start = 12,
min_zoom = 8,
max_zoom = 20,
opacity = 1
).add_to(m)
m
I'm installing geopandas and branca to use when my map becomes more complex. This is a fairly slimmed-down version of my entire code.
Problem is, the status bar doesn't begin to tick forward until the very last section of the code, when it zooms ahead to 100%. It just blinks for the first few seconds when I run this. I'd like the status bar to begin immediately upon running the very first !pip install command.
This particular chunk of code only takes a few seconds to run, but later I'll want to add a choropleth map and other shapefile layers to the map that will undoubtedly slow down the time it takes to execute. Hence, a progress bar to show the user a status would be quite helpful.

Related

Why do Calplot and and Calmap plots not show up?

When I use the examples to make a calendar heatmap and run my Python script from the terminal, I see my computer briefly open then close IDLE and the script appears to be finished running.
import numpy as np; np.random.seed(sum(map(ord, 'calplot')))
import pandas as pd
import calplot
import calmap
all_days = pd.date_range('1/1/2019', periods=730, freq='D')
days = np.random.choice(all_days, 500)
events = pd.Series(np.random.randn(len(days)), index=days)
calplot.calplot(events, cmap='YlGn', colorbar=False) # if I use this or the line above or both the same thing happens
calmap.yearplot(events, year=2019) # if I use this or the line above or both the same thing happens
I have tried installing all of the referenced libraries used by calplot and calmap, and no luck still. I have confirmed I can plot using Matplotlib, so it isn't a graphics issue

the algorithm don't display the mesh

I am using Jupyter in a Conda environment:
import igl
import meshplot as mp
import numpy as np
v, f = igl.read_triangle_mesh("./earth.ply")
k = igl.gaussian_curvature(v, f)
mp.plot(v, f, k, return_plot = True)
OUTPUT:
<meshplot.Viewer.Viewer at 0x1b53eb03fa0>
it is not displaying the mesh. it just outputs the location it stored in memory. Please help me.
It seems that you have your meshplot.rendertype set to "OFFLINE".
If you are using this code in a jupyter notebook and want to display the mesh, then just switch rendertype to "JUPYTER", by executing mp.jupyter() somewhere before your plot() command.
If you are running the code as a normal python program, you can export this View object as a HTML frame using the View.to_html() method. Then you can insert this frame into a html file and view it in a browser.
You can check out the source code for switching rendertype here, how the mp.plot function works here. The View class with the to_html method is defined here.

When I run '''sns.histplot(df['price'])''' in pycharm I get the code output but no graph, why is this?

I'm using pycharm to run some code using Seaborn. I'm very new to python and am just trying to learn the ropes so I'm following a tutorial online. I've imported the necessary libraries and have run the below code
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
# import the data saved as a csv
df = pd.read_csv('summer-products-with-rating-and-performance_2020-08.csv')
df["has_urgency_banner"] = df["has_urgency_banner"].fillna(0)
df["discount"] = (df["retail_price"] -
df["price"])/df["retail_price"]
df["rating_five_percent"] = df["rating_five_count"]/df["rating_count"]
df["rating_four_percent"] = df["rating_four_count"]/df["rating_count"]
df["rating_three_percent"] = df["rating_three_count"]/df["rating_count"]
df["rating_two_percent"] = df["rating_two_count"]/df["rating_count"]
df["rating_one_percent"] = df["rating_one_count"]/df["rating_count"]
ratings = [
"rating_five_percent",
"rating_four_percent",
"rating_three_percent",
"rating_two_percent",
"rating_one_percent"
]
for rating in ratings:
df[rating] = df[rating].apply(lambda x: x if x>= 0 and x<= 1 else 0)
# Distribution plot on price
sns.histplot(df['price'])
My output is as follows:
Process finished with exit code 0
so I know there are no errors in the code but I don't see any graphs anywhere as I'm supposed to.
Ive found a way around this by using this at the end
plt.show()
which opens a new tab and uses matplotlib to show me a similar graph.
However in the code I'm using to follow along, matplotlib is not imported or used (I understand that seaborn has built in Matplotlib functionality) as in the plt.show statement is not used but the a visual graph is still achieved.
I've also used print which gives me the following
AxesSubplot(0.125,0.11;0.775x0.77)
Last point to mention is that the code im following along with uses the following
import seaborn as sns
# Distribution plot on price
sns.distplot(df['price'])
but distplot has now depreciated and I've now used histplot because I think that's the best alternative vs using displot, If that's incorrect please let me know.
I feel there is a simple solution as to why I'm not seeing a graph but I'm not sure if it's to do with pycharm or due to something within the code.
matplotlib is a dependency of seaborn. As such, importing matplotlib with import matplotlib.pyplot as plt and calling plt.show() does not add any overhead to your code.
While it is annoying that there is no sns.plt.show() at this time (see this similar question for discussion), I think this is the simplest solution to force plots to show when using PyCharm Community.
Importing matplotlib in this way will not affect how your exercises run as long as you use a namespace like plt.
Be aware the 'data' must be pandas DataFrame object, not: <class 'pandas.core.series.Series'>
I using this, work finely:
# Distribution plot on price
sns.histplot(df[['price']])
plt.show()

qiskit plots not showing up in spyder console

System Informations
Qiskit version: 0.17.0
Python version: 3.7.7
Operating system: Windows 10 home x64
What is the current behavior?
I am using spyder 4.1.1 on Anaconda and any time I try to plot data it does not show up. The code runs with no errors but the plot it self does not appear anywhere.
Steps to reproduce the problem
Running the code listed below which is from the IBMQ website:
import numpy
import qiskit as qc
from qiskit import QuantumCircuit, execute, Aer
import matplotlib
from qiskit.visualization import plot_state_city
circ = qc.QuantumCircuit(3)
circ.h(0)
circ.cx(0,1)
circ.cx(0,2)
print(circ.draw())
backend = Aer.get_backend('statevector_simulator')
job = execute(circ, backend)
result = job.result()
outputstate = result.get_statevector(circ, decimals=3)
print(outputstate)
plot_state_city(outputstate)
What is the expected behavior?
for the plot state city plot to show up in the console or somewhere else
Suggested solutions
I tried using both matplotlib.pylot.show() and matplotlib.pyplot.draw()
Try follow the instructions under "Spyder plots in separate windows" here. Then you can also call circ.draw(output='mpl') to draw the circuit in a window. Hope this helps.
To print your circuit, you have to type print(name of the circuit) so in your case type print(circ).
This may be because the plots don't show in spyder by default. If you run this code in a Jupyter Notebook the plots should show up just fine!
I generally use pycharm ide for running the qiskit code. I think, spyder should also work the same.
Please modify your code as below. I hope, it will work for you.
import numpy
import qiskit as qc
from qiskit import QuantumCircuit, execute, Aer
import matplotlib
from qiskit.visualization import plot_state_city
import matplotlib.pyplot as plt
circ = qc.QuantumCircuit(3)
circ.h(0)
circ.cx(0,1)
circ.cx(0,2)
circ.draw(output='mpl')
backend = Aer.get_backend('statevector_simulator')
job = execute(circ, backend)
result = job.result()
outputstate = result.get_statevector(circ, decimals=3)
print(outputstate)
plot_state_city(outputstate)
plt.show()
1st: I changed the preferences of spyder: Tools ==> Preferences ==> ipython console ==> Graphics ==> Graphics backend ==> Automatic.
2nd: then I have tried the option mentioned in the answer above, with minor modification is that by writing 'mpl' only between the brackets after the word "draw" to have the code be circ.draw('mpl'), and things worked fine.

VS-Code doesn't plot gpd.GeoSeries().plot()

Hi I am trying to plot Geo-Data using VS-Code with geopandas
My code looks as follows:
import geopandas as gpd
import geopandas.geoseries
from shapely.geometry import Point
import random
import matplotlib as plt
#offset a point randomly
def point_offset(point):
x_alt = point.x
y_alt = point.y
x_neu = x_alt + random.randrange(-100,100,1)
y_neu = y_alt + random.randrange(-100,100,1)
punkt_neu = Point(x_neu,y_neu)
return punkt_neu
#define point and calculate new point
sternwarte = Point(2600000,1200000)
sternwarte_neu = point_offset(sternwarte)
print(sternwarte_neu)
#why do these two lines don't work??
ax = gpd.GeoSeries([point_offset(sternwarte) for x in range(1,1000)]).plot()
gpd.GeoSeries(sternwarte).plot(ax = ax, color = "red")
The outpot looks like this:
PS C:\Users\giebe\projects\GIS\Coding_2> cd 'c:\Users\giebe\projects\GIS\Coding_2'; ${env:PYTHONIOENCODING}='UTF-8'; ${env:PYTHONUNBUFFERED}='1'; & 'C:\Users\giebe\Anaconda\envs\buerktim\python.exe' 'c:\Users\giebe\.vscode\extensions\ms-python.python-2019.10.44104\pythonFiles\ptvsd_launcher.py' '--default' '--client' '--host' 'localhost' '--port' '54586' 'c:\Users\giebe\projects\GIS\Coding_2\Monte_Carlo.py'
POINT (2600075 1200034)
PS C:\Users\giebe\projects\GIS\Coding_2>
It seems like the program is running correctly, but the last two lines don't get exececuted (the plot doesn't show up)
In the following link it is said I can just use the .plot() Funktion to plot geodata:
http://geopandas.org/mapping.html
I copied the code from a course in uni, but they are using the Spyder IDE. I really like VS-Code because of its Autocomplete function and Intelisense.
What important part am I missing?
UPDATE: When I try to run the following code suggested by martinfleis in the comments:
world = gpd.read_file(geopandas.datasets.get_path('naturalearth_lowres'))
world.plot()
i get the following error:
"The descartes package is required for plotting polygons in geopandas."
ImportError: The descartes package is required for plotting polygons in geopandas.
When i use the, by the error message suggested import:
from descartes.patch import PolygonPatch
It doesn^t seem to find the descartes package:
Exception has occurred: ModuleNotFoundError
No module named 'descartes'
File "C:\Users\giebe\projects\GIS\Coding_2\Monte_Carlo.py", line 6, in <module>
from descartes.patch import PolygonPatch
So i installed descartes in the Terminal using
conda install descartes matplotlib
It shows up with the pip freeze command so descartes is installed.
But the error still persists.(No module named descartes)

Categories