interactive plot geopandas doesn't show - python

I have this code from this website:
https://geopandas.org/en/stable/docs/user_guide/interactive_mapping.html
import geopandas as gpd
import matplotlib.pyplot as plt
world_filepath = gpd.datasets.get_path('naturalearth_lowres')
world = gpd.read_file(world_filepath)
print(world.head())
world.explore(column='pop_est',cmap='Set2')
plt.show()
I try to run the code, the geodataframe data is printed but no plot is shown.
What am i missing?
Thnx in advanced.

world.explore(column='pop_est',cmap='Set2') should return and display a folium map object so you shouldn't need that plt.show() as the bottom.
Also, since you're using an IDE (not jupyter) we need to write the map to disk then open it up in the broswer.
Try
import geopandas as gpd
import webbrowser
import os
world_filepath = gpd.datasets.get_path('naturalearth_lowres')
world = gpd.read_file(world_filepath)
print(world.head())
# world.explore() returns a folium map
m = world.explore(column='pop_est',cmap='Set2')
# and then we write the map to disk
m.save('my_map.html')
# then open it
webbrowser.open('file://' + os.path.realpath('my_map.html'))

export() creates a folium object, not a matplotlib figure
in jupyter just have m as last item in code cell
in other environments you can save as HTML and launch into a browser
import geopandas as gpd
import webbrowser
from pathlib import Path
world_filepath = gpd.datasets.get_path('naturalearth_lowres')
world = gpd.read_file(world_filepath)
print(world.head())
m = world.explore(column='pop_est',cmap='Set2')
f = Path.cwd().joinpath("map.html")
m.save(str(f))
webbrowser.open("file://" + str(f))

Related

The graph is not showing up in my jupyter notebook in kaggle

I am not able to see my plot in my kaggle notebook.
The following is my code.
import ipywidgets as widgets
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import datetime as dt
import seaborn as sns
df = pd.read_csv('../input/sdd1247/COMED_hourly.csv', parse_dates=["Datetime"], index_col="Datetime")
def Visualization_plots(x):
y = df.loc['2017']
y['COMED_MW'].resample('H').mean().plot()
button = widgets.Button(
description='Submit',
disabled=False,
button_style='success', # 'success', 'info', 'warning', 'danger' or ''
tooltip='Click me',
icon='alicorn' # (FontAwesome names without the `fa-` prefix)
)
button.on_click(Visualization_plots)
button
The button shows up.. but when I click on it, I expected the graph to show below it. But nothing shows up.
I do however see the graph in the console. How can I show the graph in my notebook instead?
This is how it shows up in the console window:
I would add plt.show() on the line after the plot instruction.
If it doesn't work please provide a few lines of your dataset.

How can we get tooltips and popups to show in Folium

I am trying to get a tooltip and/or a popup to show on a map. When I zoom in, this is all that I see.
Here is the code that I am testing.
import folium
import requests
from xml.etree import ElementTree
from folium import plugins
m = folium.Map(location=[40.6976701, -74.2598704], zoom_start=10)
m.save('path')
for lat,lon,name,tip in zip(df_final['Latitude(DecDeg)'], df_final['Latitude(DecDeg)'], df_final['Market Description'], df_final['Project Description']):
folium.Marker(location=[lat,lon], tooltip = tip, popup = name)
m.add_child(cluster)
m
I feel like I'm missing a library, or some such thing. Any idea why this is not working correctly?
It seems you forgot to use .add_to(m) to add it to map
folium.Marker(...).add_to(m)
or
marker = folium.Marker(...)
marker.add_to(m)
Minimal working code:
import folium
import webbrowser # open file in webbrowser
m = folium.Map(location=[40.6976701, -74.2598704], zoom_start=10)
marker = folium.Marker(location=[40.6976701, -74.2598704],
tooltip='<b>Stackoverflow</b><br><br>2021.01.01',
popup='<h1>Happy New Year!</h1><br><br>www: Stackoverflow.com<br><br>date: 2021.01.01')
marker.add_to(m)
m.save('map.html')
webbrowser.open('map.html') # open file in webbrowser

Python code doesn't run, I don't know what to do to fix it

class AQGraph:
import pandas as pd
import numpy as np
import matplotlib as plt
PrimaryA = pd.read_csv('PrimaryA.csv') # Daily data from 12/1/19 to 4/16/20 from PrimaryA sensor
PrimaryB = pd.read_csv('PrimaryB.csv') # Daily data from 12/1/19 to 4/16/20 from PrimaryB sensor
AverageData = np.mean(PrimaryA[:][2], PrimaryB[:][2])
print(AverageData)
plt.plot(PrimaryA[:][0], AverageData)
plt.show()
Attached is my python code. I'm running it in Pycharm and for some reason the green arrow that pops up for Pycharm files isn't there. I've looked through my settings and I'm running Python 3.7. Any advice?
The code you provided, doesn't comply with python rules and standards.
there is a class in your code without any constructor or any method.
Also, you didn't follow Python's indentation policy. Based on what you provided, as soon as you try to run it you should see an error.
import pandas as pd
import numpy as np
import matplotlib as plt
class AQGraph:
#staticmethod
def a_method():
PrimaryA = pd.read_csv('PrimaryA.csv') # Daily data from 12/1/19 to 4/16/20 from PrimaryA sensor
PrimaryB = pd.read_csv('PrimaryB.csv') # Daily data from 12/1/19 to 4/16/20 from PrimaryB sensor
AverageData = np.mean(PrimaryA[:][2], PrimaryB[:][2])
print(AverageData)
plt.plot(PrimaryA[:][0], AverageData)
plt.show()
if __name__ == "__main__":
AQGraph.a_method()
In the command line try:
> python python_file.py

How to get Bokeh's 'PointDrawTool' working with a NetworkX Spring_Layout

I am working on a network node graph using NetworkX and Bokeh. I am using NetworkX's spring_layout to automatically generate positions for each of my nodes. However, I cannot figure out how to drag the nodes around on my graph (and also have the edges follow along with any dragged nodes).
How do I enable node-dragging for my NetworkX/Bokeh graph?
I have tried using Bokeh's 'PointDrawTool' tool, however, even though the tool renders and shows up in the toolbar next to my graph, it isn't functional.
plot = Plot(plot_width=1000, plot_height=1000,
x_range=Range1d(-1.1,1.1), y_range=Range1d(-1.1,1.1))
plot.title.text = "Network Graph"
graph_renderer = from_networkx(G, nx.spring_layout)
plot.add_tools(HoverTool(tooltips=[("ID", "#index"), ("Internal IP", "#Internal")]), PointDrawTool(renderers = [graph_renderer.node_renderer], empty_value = 'black'), TapTool(), BoxSelectTool(), BoxEditTool(), BoxZoomTool(), PanTool(), WheelZoomTool(), ZoomInTool(), ZoomOutTool(), SaveTool(), UndoTool())
graph_renderer.node_renderer.glyph = Circle(size=10, fill_color=Spectral4[0])
graph_renderer.node_renderer.selection_glyph = Circle(size=10, fill_color=Spectral4[2])
graph_renderer.node_renderer.hover_glyph = Circle(size=10, fill_color=Spectral4[1])
graph_renderer.edge_renderer.glyph = MultiLine(line_color="#CCCCCC", line_alpha=0.8, line_width=1)
graph_renderer.edge_renderer.selection_glyph = MultiLine(line_color=Spectral4[2], line_width=3)
graph_renderer.edge_renderer.hover_glyph = MultiLine(line_color=Spectral4[1], line_width=3)
graph_renderer.selection_policy = NodesAndLinkedEdges()
graph_renderer.inspection_policy = NodesAndLinkedEdges()
plot.renderers.append(graph_renderer)
output_file("interactive_graphs.html")
show(plot)
I expect the nodes to be draggable. I want to click on a node and drag it so that it changes its position.
14/05/2019 Edit:
My imports:
import pandas as pd
import numpy as np
import networkx as nx
from bokeh.io import show, output_file
from bokeh.models import Plot, Range1d, MultiLine, Circle, HoverTool, TapTool, BoxEditTool, BoxSelectTool, BoxZoomTool, ResetTool, PanTool, WheelZoomTool, ZoomInTool, ZoomOutTool, SaveTool, UndoTool, PointDrawTool
from bokeh.models.graphs import from_networkx, NodesAndLinkedEdges, EdgesAndLinkedNodes
from bokeh.palettes import Spectral4
import warnings
import matplotlib.pyplot as plt
%matplotlib notebook
from IPython.display import display, HTML
from IPython.core.interactiveshell import InteractiveShell
From: https://discourse.bokeh.org/t/networkx-import-and-pointdrawtool/3512
"The proximate cause of the problem is that the tool requires access to
glyph.x.field and glyph.y.field but both of these are null for the Circle node
renderer. The GraphRenderer is the only example of a “composite” renderer, so it’s
entirely possible (probable) that there is some interaction problem specific to it
with the PointDrawTool. The next appropriate step would be to make a bug report
issue on GitHub 5 with details."
It would be nice if they solved it.

Plotting Candle Stick in Python

I am trying to plot a candle stick chart in python. Here is my code
from pandas_datareader import data as pdr
import plotly.plotly as py
import plotly.graph_objs as go
import fix_yahoo_finance as yf
yf.pdr_override()
mcd = pdr.get_data_yahoo("MCD", start="2004-01-01", end="2005-07-31")
mcd_candle = go.Candlestick(x=mcd.index,open=mcd.Open,high=mcd.High,low=mcd.Low,close=mcd.Close)
data = [mcd_candle]
py.iplot(data, filename='Candle Stick')
This is the error I am getting
PlotlyError: Because you didn't supply a 'file_id' in the call, we're assuming you're trying to snag a figure from a url. You supplied the url, '', we expected it to start with 'https://plot.ly'.
Any idea how I can draw a Candle Stick Chart?
The problem must be because you didn't provide the username and api key which you will get from the https://plot.ly/settings/api link. If you want to use plotly online to create this graph. First create an account, then get the username and api key and insert it in the below code.
from pandas_datareader import data as pdr
import plotly.plotly as py
import plotly.graph_objs as go
import fix_yahoo_finance as yf
py.sign_in('<<username here>>', '<<api key here>>')
yf.pdr_override()
mcd = pdr.get_data_yahoo("MCD", start="2004-01-01", end="2005-07-31")
mcd_candle = go.Candlestick(x=mcd.index,open=mcd.Open,high=mcd.High,low=mcd.Low,close=mcd.Close)
data = [mcd_candle]
py.iplot(data, filename='Candle Stick')
There is another option of using plotly offline which does not need all this procedure, please find below the implementation code.
from pandas_datareader import data as pdr
import plotly.offline as py_offline
import plotly.graph_objs as go
import fix_yahoo_finance as yf
py_offline.init_notebook_mode()
yf.pdr_override()
mcd = pdr.get_data_yahoo("MCD", start="2004-01-01", end="2005-07-31")
mcd_candle = go.Candlestick(x=mcd.index,open=mcd.Open,high=mcd.High,low=mcd.Low,close=mcd.Close)
data = [mcd_candle]
py_offline.iplot(data, filename='Candle Stick')
#for Spyder plotting use the below line instead
#py_offline.plot(data, filename='Candle Stick')
Please make sure to install the libraries pandas_datareader and fix_yahoo_finance using pip, if these libraries are not already present!

Categories