I have a GeoJSON file that records a city's roads geocodes and their attributes. Sample looks like this
{"type":"FeatureCollection", "features": [
{"type":"Feature","geometry":
{"type":"LineString","coordinates":[[lat1, long1],[lat2, long2],[lat3, long3]]},
"properties":{"ROUTE_TYPE":,"TOTAL_LANE":,"AADT":}}}}
In this case, how can I convert such JSON to a networkX graph?
Ideally a DiGraph (I do notice that direction information is not indicted in the JSON at all. I am fine with assuming all links are bidirectional.)
This question is similar to the following question on GIS stackexchange: Retrieving OpenStreetMap data with Python using GeoJSON geometry as boundary and its answer.
The main ingredients you need are the following:
geopandas to parse the geojson into a GeoDataFrame with read_file
OSMnx to transform the GeoDataFrame into a networkx.MultiDiGraph using osmnx.utils_graph.graph_from_gdfs
Alternatively, you could use ignore_geometry=Truein the first step and use nx.from_pandas_edgelist
Related
I wrote code below to show graph with igraph package, But I don't know How can I export igraph result in csv file in python? and my another question is how can I add label?
import igraph as ig
import pandas as pd
g=ig.Graph.TupleList(df.itertuples(index=False),directed=True)
ig.plot(g, target='graph.png', vertex_size=10, bbox=(0, 0, 500, 500))
Because I want to import that in gephi application I need csv file
Here is the list of formats that igraph can export to:
https://igraph.org/python/api/latest/igraph.Graph.html#write
This is the list of formats supported by Gephi:
https://gephi.org/users/supported-graph-formats/
Choose one that is common to both and use that. I would try GraphML first.
If you insist on CSV-like formats, NCOL comes closest. You can also use the get_edgelist() method to get the list of vertex pairs representing edges, then export them using Python's own facilities.
I have been using textnets (python) to analyse a corpus. I need to export the resulting graph for further analysis / layout editing in Gephi. Having read the docs I am still confused on how to either save the resulting igraph Graph in the appropriate format or to access the pandas dataframe which could then be exported. For example using the tutorial from docs, if using:
from textnets import Corpus, Textnet
from textnets import examples
corpus = Corpus(examples.moon_landing)
tn = Textnet(corpus.tokenized(), min_docs=1)
print(tn)
I had thought I could either return a pandas data frame by calling 'tn' though this returns a 'Textnet' object.
I had also thought I could return an igraph.Graph object and then subsequently use Graph.write_gml() using something like tn.project(node_type='doc').write_gml('test.gml') to save the file in an appropriate format but this returns a ProjectedTextnet.
Any advise would be most welcome.
For the second part of your question, you can convert the textnet object to an igraph:
g = tn.graph
Then save as gml:
g.write_gml("test.gml")
I am using the PlyFile library (https://pypi.org/project/plyfile) in Python.
I used vertex = plydata['vertex'] to generate a list of vertex co-ordinates. The datatype is as follows -
PlyElement('vertex', (PlyProperty('x', 'float'), PlyProperty('y', 'float'), PlyProperty('z', 'float')), count=2500086, comments=[])
After that I generated a list of all the x-axis values and put them into a numpy array and performed some operations on them. Then I replaced the original x-axis values in plydata['vertex'] with these new ones.
Now I want to write these values into a .ply file and create a new mesh. How would I go about it? I tried going through the docs but the code is quite messy.
Any insights would help, Thanks!
Saving a .ply file:
ply_data: PlyData
ply_data.text = True # for asci format
ply_data.write(path)
My goal is to get a so-called "choropleth map" (I guess) of the zip code areas in Germany. I have found the python package "folium" but it seems like it takes a .json file as input:
https://github.com/python-visualization/folium
On OpenStreetMap I only see shp.zip and .osm.pbf files. Inside the shp.zip archive I find all sorts of file endings which I have never heard of but no .json file. How do I use the data from OpenStreetMap to feed folium? Am I running into the wrong direction?
If you want to create a choropleth map you must follow these steps:
First you need a file containing info about the regions of that country. A sample .json file has been supplied with this answer, however, there are actually many file formats commonly used for maps. In your case, you need to convert your OSM shape file (.shp) into a more modern file type like .geojson. Thankfully we have ogr2ogr to do this last part:
ogr2ogr -f GeoJSON -t_srs EPSG:4326 -simplify 1000 [name].geojson [name].shp
Advice: You can also extract the administrative borders from these web sites:
* [OSM Boundaries Map 4.2][2]
* [Mapzen][3]
* [Geofabrik][4]
Download data based on it (a .csv file, for example). Obviously, the file must have a column with the ZIP Codes of that country.
Once you get these files the rest is straightforward, Follium will create the choropleth map automatically.
I wrote a simple example of this about the unemployment rate in the US:
Code:
import folium
import pandas as pd
osm = folium.Map([43, -100], zoom_start=4)
osm.choropleth(
geo_str = open('US_states.json').read(),
data = pd.read_csv("US_unemployment.csv"),
columns = ['State', 'Unemployment'],
key_on = 'feature.id',
fill_color = 'YlGn',
)
Output:
I haven't done this myself but there are various solutions for converting OSM files (.osm or .pbf) to (geo)json. For example osmtogeojson. More tools can be found at the GeoJSON page in the OSM wiki.
I went to https://overpass-turbo.eu/ (which retrieves data from openstreetmap via a specific Query Language QL) and hit run on the following code:
[timeout:900];
area[name="Deutschland"][admin_level=2][boundary=administrative]->.myarea;
rel(area.myarea)["boundary"="postal_code"];
out geom;
You can "export to geojson" but in my case that didn't work because it's too much data which cannot be processed inside the browser. But exporting the "raw data" works. So I did that and then I used "osmtogeojson" to get the right format. After that I was able to feed my openstreetmap data to folium as described in the tutorial of folium.
This answer was posted as an edit to the question Choropleth map with OpenStreetMap data by the OP user3182532 under CC BY-SA 3.0.
I want to import a geojson file into python so I can map it with a visualization package vincent and merge with other data in a pandas data frame.
To be specific, the said geojson file is: http://ec2-54-235-58-226.compute-1.amazonaws.com/storage/f/2013-05-12T03%3A50%3A18.251Z/dcneighorhoodboundarieswapo.geojson. It's a map of DC with neighborhoods, put together by Justin Grimes.
Right now, I'm just trying to visualize this map on notebook. Here's my code:
import vincent
map=r'http://ec2-54-235-58-226.compute-1.amazonaws.com/storage/f/2013-05-12T03%3A50%3A18.251Z/dcneighorhoodboundarieswapo.geojson'
geo_data = [{'name': 'countries',
'url': map,
'feature': "features"}]
vis = vincent.Map(geo_data=geo_data, scale=5000)
vis
but I keep getting an error message, local host says: [Vega err] loading failed.
What am I doing wrong here?
I don't yet know much about GIS and Python so I ask you be specific in your explanation. Thank you in advance.
At this moment you can't use for you maps with vincent anything but topojson file format (see https://github.com/mbostock/topojson/wiki).
You can convert geojson into topojson using web tools like https://mapshaper.org/ or using command-line utility (https://github.com/mbostock/topojson/wiki/Command-Line-Reference) with command like this:
topojson -p -o <target-file>.topo.json -- <input-file>.json
(-p says utility to keep properties of geometries.)