I'm using kepler.gl to create some geographical plots.
I want to create some setting for the plot and than set these as default for when I run the cell containing that plot.
These are the steps:
I copied the conf from Kepler.gl website from Share>Share Map> Map Config.
I pasted the copied text to my python notebook cell in the variable
conf
conf = {. . .} # copied from the website after setting the correct visualization
I replaced all true with True, false with False etc.
In the notebook I created a map and set the config
from keplergl import KeplerGl
import json
map1 = KeplerGl()
map1.add_data(data=gpd.read_file('my.geojson'), name='name1')
map1.config = conf
I modified the label property in conf so that it would be equal to the name property inside the add_data function
Finally when I show the plot using
map1
It shows a basic plot of my geojson without any of the configurations in conf.
NB.
The geojson file I uploaded in Kepler.gl is the same file I used in KeplerGL() python function
I read online that it can be due to the IDs of the datasets but I don't understand how to make those IDs the same since I'm using the same dataset.
Here's the documentation, personally I didn't manage to find the answer to my question in there but maybe there is and I didn't understand it.
You need to pass the value of the name that you define in the
map1.add_data()to the dataId property (instead of the label) of your config.
So in your exapmpe:
"dataId": ["name1"]
đź’ˇImportant: Depending on your style settings the field "dataId" might exist more than once. You need to replace the value of all instances.
Related
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'm writing an interactive visualization code using Python.
What i would like to do is to create an interactive visualization which allows the user to select a file from a dropdown menu (or something like that) and then plot a barplot of the selected data.
My data folder has the following structure:
+-- it_features
| +-- it_2017-01-20--2017-01-27.csv
| +-- it_2017-01-27--2017-02-03.csv
| +-- it_2017-02-03--2017-02-10.csv
and so on (there are many more files, I'm just reporting few of them for simplicity).
So far I'm able to access and retrieve all the data contained in the folder:
import os
import pandas as pd
path = os.getcwd()
file_folder = os.path.join(path,'it_features')
for csv_file in os.listdir(file_folder):
print(csv_file)
file = os.path.join(file_folder,csv_file)
df = pd.read_csv(file)
#following code....
What I would like to do is create an insteractive visualization which allows the user to select the file name (for example it_2017-02-03--2017-02-10.csv) and plot the data of that file.
I'm able to select "by hand" the file I want and plot its data by inserting its filename in a variable and then retrieving the data, but I would like not to insert it via code and allow the final user to browse and select one of the files using a dropdown menu or something similar.
My simple code:
import os
import pandas as pd
path = os.getcwd()
file_folder = os.path.join(path,'it_features')
file = os.path.join(file_folder,'it_2020-02-07--2020-02-14.csv') # Here I insert my filename
df=pd.read_csv(file)
ax=df.value_counts(subset=['Artist']).head(10).plot(y='number of songs',kind='bar', figsize=(15, 7), title="7-14 February 2020")
ax.set_xlabel("Artist")
ax.set_ylabel("Number of Songs Top 200")
Which generates the following plot:
As I already said, I would like to introduce a somewhat drodown menu that allows the user to select the csv data he wants to plot using an interactive plot.
I saw that it's possible to create dropdown menus with Plotly, but in the various examples (https://plotly.com/python/dropdowns/) it doesn't seem to select and then load the data.
I also saw this code (Kaggle code) which seems to do what I wanted to do: you can select the region and plot the data from that region.
The main problem is that he just creates a big unique dataframe with US states, and then creates a trace for each one of them.
What i would like to do (if possible) is to select the file name from the dropdown, load the csv and then plot its data, without creating a single giant dataframe with all my files in it.
Is it possible?
EDIT: The solution proposed by gherka works perfectly, but I would like to have a solution inside Plotly using its dropdown menu.
Since you're working in Jupyter Notebook, you have a number of different options.
Some visualisation libraries will have built-in widgets that you can use, however they would often require you to run a server or provide a javascript callback. For a library-agnostic approach, you can use ipywidgets. This library is specifically for creating widgets to be used in Jupyter Notebooks. The documentation is here.
To create a simple dropdown with a static bar plot underneath, you would need three widgets - Label for dropdown description, Dropdown and Output. VBox is for laying them out.
from ipywidgets import VBox, Label, Dropdown, Output
desc = Label("Pick a .csv to plot:")
dropdown = Dropdown(
options=['None', 'csv1', 'csv2', 'csv3'],
value='None',
disabled=False)
output = Output()
dropdown.observe(generate_plot, names="value")
VBox([desc, dropdown, output])
The key element is the generate_plot function. It must have a single parameter that you use to decide what effect the widget action has on your plot. When you interact with the dropdown, the generate_plot function will be called and passed a dictionary with "new" value, "old" value and a few other things.
Here's a function to generate a basic seaborn bar chart with an adjustable data source. Notice I had to include an explicit plt.show() - plots won't render otherwise.
def generate_plot(change):
with output:
output.clear_output() # reset the view
if change["new"] != "None":
data = pd.read_csv(...) # your custom code based on dropdown selection
sns.catplot(x="Letters", y="Numbers", kind="bar", data=data)
fig = plt.figure()
plt.show(fig)
If you have many large .csv files, one other thing is you might want to do is implement a caching system so that you keep the last few user selections in memory and avoid re-reading them on each selection.
For a more in-depth look at how to add interactivity to matplotlib plots using ipywidgets I found this tutorial quite useful.
tkinter is a super common UI framework for python, and is part of the standard library. Based on answers in a similar question, you can use this:
from tkinter.filedialog import askopenfilename
filename = askopenfilename()
which pops up a standard file explorer window.
I'm new to q and I'm trying to save a file on my Mac. Currently using Jupyter Notebook if that makes a difference.
A quick table:
t:([] c1:`a`b`c; c2:1.1 2.2 3.3)
I first extract my current location by using \cd and i get: "/Users/Gorlomi/Documents/q"
but when I try
`:/Users/Gorlomi/Documents/q set t
I get:
evaluation error:
type
[1] (.q.set)
[0] `:/Users/Gorlomi/Documents/q set t
^
I'm following examples from "Q for Mortals" from the kx website:
https://code.kx.com/q4m3/1_Q_Shock_and_Awe/#11-starting-q
For easy find use cmd (or ctrl) + F and find "t set t"
Thank you in advance.
There are two answers to this question, depending on whether you want to save your file as a flat table, or a splayed table.
If you want to save you table as a flat table, you need to give a file name for your table. Currently, you're just giving it the directory that you want to save it in. So for instance, the following should work for you:
`:/Users/Gorlomi/Documents/q/t set t
If instead, you want to save your table as a splayed table, then you will need to pass it a directory (ideally, one that is not already being used by the file system). To do this, you will pass set a file path with a trailing forward slash. So the following should work for you:
`:/Users/Gorlomi/Documents/q/t/ set t
Django and Python newbie here. Ok, so I want to make a webpage where the user can enter a number between 1 and 10. Then, I want to display an image corresponding to that number. Each number is associated with an image filename, and these 10 pairs are stored in a list in a .txt file.
One way to retrieve the appropriate filename is to create a NumToImage model, which has an integer field and a string field, and store all 10 NumToImage objects in the SQL database. I could then retrieve the filename for any query number. However, this does not seem like such a great solution for storing a simple .txt file which I know is not going to change.
So, what is the way to do this in Python, without using a database? I am used to C++, where I would create an array of strings, one for each of the numbers, and load these from the .txt file when the application starts. This vector would then lie within a static object such that I can access it from anywhere in my application.
How can a similar thing be done in Python? I don't know how to instantiate a Python object and then enable it to be accessible from other Python scripts. The only way I can think of doing this is to pass the object instance as an argument for every single function that I call, which is just silly.
What's the standard solution to this?
Thank you.
The Python way is quite similar: you run code at the module level, and create objects in the module namespace that can be imported by other modules.
In your case it might look something like this:
myimage.py
imagemap = {}
# Now read the (image_num, image_path) pairs from the
# file one line at a time and do:
# imagemap[image_num] = image_path
views.py
from myimage import imagemap
def my_view(image_num)
image_path = imagemap[image_num]
# do something with image_path
My problem is that I wanna make a config file for an application but things aren't as simple as they seamed. So I've seen a tutorial where a config file contained the width and the height and the values that followed the equal sign could been retrieved and used to establish the size of a frame. Been there, done that, and everything worked okey. Strangely enough this seams to work only for some key words, as if I've used in the config file, also a parameter named freq it didn't retrieved its value as it did with the width, height parameters.
for example if I have a piece of code like this:
self.cfg = wx.Config('myconf')
wid = self.cfg.ReadInt('width')
hei = self.cfg.ReadInt('height')
freq = self.cfg.ReadInt('frequency')
print wid, hei, freq
where in myconf
width=400
height=250
frequency=3000
So it displays the height, the width but not the frequency, as for freq it gives only 0, and this happens for any other word I use in the config file. I'm guessing that only certain key words can be used in the config file, so they could be recognized while using wxPython.
If so where could I get a list of those keys I could use in making a configuration file ?
Personally, I would recommend using ConfigParser which comes with Python or perhaps ConfigObj (which I like better). If you're trying to save widget attributes / settings, then you also might want to look at the PersistenManager
What you could do is reading the lines yourself:
F = open('myconf', 'r')
for line in F.read().split('\n'):
switchres = { 'frequency': print(line.split('=')[1]),
# add the rest
}
switchres[line.split('=')[0]]
wxPython is a wrapper (or binding) for wxWidgets that is a C++ library.
So wx.Config or wx.FileConfig is intended for C++ that has no specific way of treating these type of config file (still wx.Config is meant to be portable between platforms).
In Python you already have ConfigParser module, but have in mind:
that some wxPython classes work with wx.Config like wx.FileHistory,
use wx.Config if you want to use the platform specific way of storing configurations (like registry in Windows).