Last active
October 6, 2020 16:41
-
-
Save lucharo/37587760e7f7f9623f60fb6e46a80644 to your computer and use it in GitHub Desktop.
Populate plotly.go.Figure['data']
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#1 Assign color to each unique item | |
from random import sample | |
colors = {item: 'rgb({}, {}, {})'.format(*sample(range(256), 3)) for item in data['Item'].unique()} | |
data['color'] = data['Item'].map(colors) | |
#2 Slice data, select earliest date available | |
##2.1 Select earliest year available | |
frame1 = data[data['Year'] == data['Year'].min()] | |
##2.2 Sort the data by value and get the top 10 entries | |
top_entries = 10 # modify to get top 5, top 20 or any other | |
frame1 = frame1.sort_values('Value', ascending = False).iloc[:top_entries, :] | |
##2.3 Sort values in ascending order so that top bar corresponds to greatest value | |
frame1 = frame1.sort_values('Value', ascending = True) | |
#3 Populate data entry in plotly figure with frame1 | |
fig['data'] = go.Bar( | |
x = frame1['Value'], | |
y = frame1['Item'], | |
marker_color = frame1['color'], | |
hoverinfo = 'all', # display Item name and Value when hovering over bar | |
textposition = 'outside', # position text outside bar | |
texttemplate = '%{y}<br>%{x:.4s}', # display y field (Item name), line break and then the value with up to 4 digits | |
orientation = 'h' # to have bar growing rightwards | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment