Display first ten cols of Altair chart if no user selection? - altair

My graph contains 90 rows of different companies. It's controlled by a dropdown menu that allows users to select an individual company. However, until a user selects a value from the dropdown, ALL the rows are displayed all my graph, which looks messy. Is there anyway to show only the first company by default? Or the first ten companies? Thanks.
Current Output.
Desired Output
I haven't found any solutions thus far. Here is my current code.
dropdown_list = df["Name"].sort_values().unique().tolist()
dropdown = alt.binding_select(options=[None] + dropdown_list, labels = ['All'] + dropdown_list, name = "Operator")
selection = alt.selection_single(fields=["Name"], bind=dropdown)
`(alt.Chart(df).mark_circle(opacity=1, size = 150).transform_window(id='rank()',groupby=['Variable']).encode(alt.X('Percentage:O', sort='ascending', axis=alt.Axis(ticks=False, grid=False)),
alt.Y('Name:N'),
color=alt.Color("Variable:N", scale=alt.Scale(range=cp.CALITP_CATEGORY_BRIGHT_COLORS), legend=None),
tooltip = ['Name', 'Variable'])
.properties(title = "Title Here").add_selection(selection).transform_filter(selection))`

Related

Listbox resizing itself when new data is added

I am trying to add information to my Listbox and keeping it the size I state when I configure it. Here is my code for the Listbox with the scrollbar and an image of what it looks like.
Picture of the listbox.
taskList = Listbox(setBox, bg="#1B2834",fg="white")
taskList.configure(width=183,height=39)
taskList.pack(side=LEFT,fill=BOTH)
taskScroll = Scrollbar(setBox)
taskScroll.configure(bg="#1B2834",width=18)
taskScroll.pack(side = RIGHT, fill = BOTH)
taskList.config(yscrollcommand = taskScroll.set)
taskScroll.config(command = taskList.yview)
Now, when i click a button the command is to execute this following code:
def savetasks():
#make tasks
letters = string.ascii_uppercase
result_str = ''.join(random.choice(letters) for i in range(4))
num = str(random.randrange(0,9))
taskIDnum = num+result_str
taskIDLBL = Label(taskList, text=taskIDnum,bg="#1B2834", fg="White")
taskIDLBL.configure(padx=20,pady=10)
taskIDLBL.pack()
This code works fine as well, creating new labels with a random ID but it resizes the listbox to look like this...
Picture of the list box after clicking the button to execute the command.
Lastly, the scroll bar is not scrollable and when I create a lot of id's that end up going off my screen I cannot use the scroll bar to scroll down to see them, is there a way to not let the Listbox be resized and is it possible to set the Listbox with max and min-height?
If there is an easier way to do this without using a Listbox please let know, I just need to able to scroll down to see all the other id's and I didn't see any other way to use a scroll bar, that I NEEDED to use a Listbox

Interactive labeling of images in jupyter notebook

I have a list of pictures:
pictures = {im1,im2,im3,im4,im5,im6}
Where
im1:
im2:
im3:
im4:
im5:
im6:
I want to assign the pictures to labels (1,2,3,4 etc.)
For instance, here pictures 1 to 3 belong to label 1, picture 4 belongs to label 2, picture 5 to label 3, and picture 6 to label 4.
-> label = {1,1,1,2,3,4}
Since I need to see the images when I label them, I need a method to do that while labeling them. I was thinking of creating an array of images:
And then I define the ranges by clicking on the first and last picture belonging to the same labels, so for example:
What do you think ? Is this somehow possible ?
I would like to assign different labels to different ranges of pictures.
For instance: When one has finished selecting the first label one could indicate it by a Double-click and then do the selection of the second label range, then Double-click, then do the selection of the third label range, then Double-click, then do the selection of the fourth label range, etc.
It does not have to be Double-clicking to change the selection of the labels, it could also just be a buttom or any other idea that you might have.
In the end one should have the list of labels.
Essentially, most of the interaction you are looking for boils down to being able to display images, and detect clicks on them in real time. As that is the case, you can use the jupyter widgets (aka ipywidgets) module to achieve most (if not all) of what you are looking for.
Take a look at the button widget which is described here with explanation on how to register to its click event. The problem - we can't display an image on a button, and I didn't find any way to do this within the ipywidgets documentation. There is an image widget, but it does not provide an on_click event. So construct a custom layout, with a button underneath each image:
COLS = 4
ROWS = 2
IMAGES = ...
IMG_WIDTH = 200
IMG_HEIGHT = 200
def on_click(index):
print('Image %d clicked' % index)
import ipywidgets as widgets
import functools
rows = []
for row in range(ROWS):
cols = []
for col in range(COLS):
index = row * COLS + col
image = widgets.Image(
value=IMAGES[index], width=IMG_WIDTH, height=IMG_HEIGHT
)
button = widgets.Button(description='Image %d' % index)
# Bind the click event to the on_click function, with our index as argument
button.on_click(functools.partial(on_click, index))
# Create a vertical layout box, image above the button
box = widgets.VBox([image, button])
cols.append(box)
# Create a horizontal layout box, grouping all the columns together
rows.append(widgets.HBox(cols))
# Create a vertical layout box, grouping all the rows together
result = widgets.VBox(rows)
You can technically also write a custom widget to display an image and listen for a click, but I simply don't believe it's worth your time and effort.
Good luck!
The qsl package provides widgets that do this. For your case, the following code would allow you to label images in batches. Full disclosure, qsl is a project I started because I, like you, wanted to label images from inside Jupyter notebooks.
import qsl
from IPython.display import display
labeler = qsl.MediaLabeler(
items=[
{"target": "https://i.stack.imgur.com/cML6z.jpg"},
{"target": "https://i.stack.imgur.com/6EVAP.jpg"},
{"target": "https://i.stack.imgur.com/CAxUw.jpg"},
{"target": "https://i.stack.imgur.com/8fhan.jpg"},
{"target": "https://i.stack.imgur.com/eMXn5.jpg"},
{"target": "https://i.stack.imgur.com/YFBfM.jpg"}
],
# Optional, you can also configure the labeler from
# the UI.
config={
"image": [
{
"name": "Type",
"options": [
{"name": "Foo"},
{"name": "Bar"}
]
}
]
},
# Optional, set to 1 if you want to label
# one image at a time.
batch_size=4,
# Optionally, save labels to JSON. You
# can also get the labels using `labeler.items`.
jsonpath="labels.json"
)
display(labeler)
This generates a UI that looks like this.
Here is a Google Colab notebook that shows how to do this in Google Colab.

choosing a specific button from a list of identical buttons

I am making a battleships program, and after i created a list of identical buttons for a grid and inserting them all into one list, i want to be able to choose the button just clicked and delete it. How can i achieve this?
l = []
for i in range (100):
b = Button(battleship.frame, height = 1, width = 3, command = )
l.append(b)
#this is a snippet of what i have now but i am not sure what to do.
I have tried using lambda to give each button something unique to make them all different but i don't think this helps me in selecting the specific button that was just clicked.
Any suggestions?

Bokeh: Control colors on Donut chart

I am using Bokeh to create a series of pie charts with bokeh.charts.Donut. The charts are based off of subsets of the same DataFrame, and all have the same category labels. I want to ensure that the same categories are displayed in the same colors across the various charts, but I haven't been able to figure out a consistent way of controlling the colors.
Currently I am sorting my input DataFrames by the label, and passing the same array of colors to the palette property of Donut. This still does not work as intended. Code is as follows:
main_colors = ['#10A400','#DB5E11','#C8C500','#CF102E','#00AFA8','#82BC00','#A40D7A','#FF7100','#1349BB']
#split out youth health problems
for_youth_health = detailed_assessment_safety.loc[detailed_assessment_safety.youth_health_prob.notnull()]
youth_health_issues = pd.DataFrame(for_youth_health.youth_health_prob.str.split(' ').tolist())
for col in youth_health_issues.columns:
newcol = 'youth_health_prob_' + str(col)
youth_health_issues = youth_health_issues.rename(columns={col:newcol})
youth_health_trans = pd.melt(youth_health_issues)
youth_health_trans = youth_health_trans.loc[youth_health_trans.value.notnull()]
youth_health_trans['issue_text'] = youth_health_trans.value.map(map_health_issues)
youth_health_trans.drop('value',axis=1,inplace=True)
youth_health_trans.sort_values(by='issue_text',ascending=True,inplace=True)
#pie of youth health issues
youth_health_issues = Donut(youth_health_trans,label='issue_text',
values='variable',agg='count',plot_width=plot_width,
plot_height=plot_height,title='Reported Youth Health Issues',
color=main_colors)
hover = HoverTool(point_policy='follow_mouse')
hover.tooltips = [('Number Reported','#values'),('Health Issue','#issue_text')]
youth_health_issues.add_tools(hover)
#split out adult health problems
for_adult_health = detailed_assessment_safety.loc[detailed_assessment_safety.adult_health_prob.notnull()]
adult_health_issues = pd.DataFrame(for_adult_health.adult_health_prob.str.split(' ').tolist())
for col in adult_health_issues.columns:
newcol = 'adult_health_prob_' + str(col)
adult_health_issues = adult_health_issues.rename(columns={col:newcol})
adult_health_trans = pd.melt(adult_health_issues)
adult_health_trans = adult_health_trans.loc[adult_health_trans.value.notnull()]
adult_health_trans['issue_text'] = adult_health_trans.value.map(map_health_issues)
adult_health_trans.drop('value',axis=1,inplace=True)
adult_health_trans.sort_values(by='issue_text',ascending=True,inplace=True)
#pie of adult health issues
adult_health_issues = Donut(adult_health_trans,label='issue_text',
values='variable',agg='count',plot_width=plot_width,
plot_height=plot_height,title='Reported Adult Health Issues',
palette=main_colors)
hover = HoverTool(point_policy='follow_mouse')
hover.tooltips = [('Number Reported','#values'),('Health Issue','#issue_text')]
adult_health_issues.add_tools(hover)
What's the proper way to map the same categories of Donut charts to colors across multiple charts? The other idea that I had was inserting a column into the DataFrame that mapped label values to colors, and then passing that column as an argument to Donut, but I couldn't make that work either. Any help is much appreciated.
After some experimentation, it turns out that when you pass an array of colors to the palette argument of Donut, the colors are associated with the donut slices based on an alphabetical sort of the slice name. So, the first color in your array of palette colors will be associated with the slice with the alphabetically first name, etc.

Combobox values appearing as single string characters

I am new posting to the forums & utilizing python/tkinter in order to create an electronic form to gather issues from manufacturing floor.
I have a (2) comboboxes.
The 1st combobox gains its "values" from a given dictionary.keys() which updates the "values" of a 2nd combobox. However, when selecting the values for the 2nd combobox after selecting for the 1st combobox, the values only show singular characters from the dictionary.values().
Here is the list from the txt file. The first item on each line is the key, while the rest of the items on the same line are its values.
Bondshop, Plies: Layup Difficulty, Plies: Cutting Edge
IB Postbond, POU, Equipment, Inspection, Available Work Space, Big Paint, 1575, QN
General Postbond, Inspection
Seal Area, Inspection
Big Paint, Inspection
Deflash, Inspection
Why does my 2nd combobox appear as so? See below.
"...show singular characters"...
===snip===
def loadcategory(self):
# Reads production areas & cateogries from dictCategory.txt file
self.textfileCategory = open('dictCategory.txt', 'r')
self.lines_category = self.textfileCategory.readlines()
for line in self.lines_category:
splitLine = line.split(',')
dict_category[str(splitLine[0])] = ",".join(splitLine[1:])
self.textfileCategory.close()
===snip===
def UpdateData(self, event):
# Updates Category Combobox based on Production Area selection
self.menu_category.set('---')
category = self.menu_production_area.get()
self.menu_category['values'] = sorted(dict_category[category])
===snip===
self.menu_production_area = ttk.Combobox(Main_Frame, state='readonly', values = sorted(list(dict_category.keys())), width=25)
self.menu_production_area.bind('<<ComboboxSelected>>', self.UpdateData)
self.menu_production_area.grid(row=2, column=1, sticky='w')

Resources