Bokeh Tooltips on annular wedge : extra information always present - python

I have created the following doughnut chart in bokeh, using annular_wedge glyphs. I've created a tooltip, that shows percents & category properly for each wedge, but always includes an extra category : ??? and percents:1
Why is it appearing, and how can I remove it ?
Here's a link to the notebook used for generating the plot : link
# define starts/ends for wedges from percentages of a circle
percents = [0, 0.14, 0.22, 0.40, 0.83, 0.99, 1.0]
category = ['Extreme ', 'High ', 'Light ', 'Medium ', 'Not Classified', 'Very Light ']
starts = [p*2*pi for p in percents[:-1]]
ends = [p*2*pi for p in percents[1:]]
# a color for each pie piece
colors = brewer['Spectral'][len(percents)]
# create source
source = ColumnDataSource(
data=dict(
x=[0 for x in percents],
y=[0 for x in percents],
ymin = [0.5 for x in percents],
ymax = [1 for x in percents],
percents=percents,
category= category,
starts=starts,
colors=colors,
ends=ends,
)
)
# create chart
TOOLS = "hover"
p = bk.figure(title='Chronic',title_text_font ='Roboto', title_text_font_size ='14pt', title_text_alpha =0.7,
x_range=(-1.1,1.1), y_range=(-1.1,1.1), width=250, height=250, tools=TOOLS)
p.annular_wedge(x='x', y='y', inner_radius='ymin', outer_radius='ymax', direction="anticlock",
start_angle='starts', end_angle='ends', color='colors', source=source)
hover = p.select(dict(type=HoverTool))
hover.tooltips = [
('category', '#category'),
('percents','#percents')
]
# displays
bk.show(p)

I solved the problem by setting these values directly in the function call:
p.annular_wedge(x=0, y=0, inner_radius=0.5, outer_radius=1, ... )

Related

Is there a feature to add text on the Polyline? (Python Folium)

I want to add text on the lines added using Polyline from within the folium library.(etc "1km" or "1ft")
m = folium.Map(location=[41.08468198029149, 28.8180159802915])
points = [[41.0370023, 28.9850917], [40.98186700000001, 29.0576302]]
for point in points:
folium.Marker(point).add_to(m)
folium.PolyLine(points, color="red", weight=2.5, opacity=1).add_to(m)
Something like that
[EDIT]
I find it!
Check it out
line = folium.PolyLine(points, color="red", weight=2.5, opacity=1)
attr = {'fill': '#007DEF', 'font-weight': 'bold', 'font-size': '24'}
wind_textpath = plugins.PolyLineTextPath(line,
"20 km",
center=True,
offset=7,
attributes=attr)
m.add_child(line)
m.add_child(wind_textpath)

Not able to view US-states heatmap

I have written the following code to heat heatmap of US-States. But I am unable to get the output image in Google Colab.
State codes are two alphabet codes for a particular state of the US.
temp = pd.DataFrame(project_data.groupby("school_state")["project_is_approved"].apply(np.mean)).reset_index()
temp.columns = ['state_code', 'num_proposals']
scl = [[0.0, 'rgb(242,240,247)'],[0.2, 'rgb(218,218,235)'],[0.4, 'rgb(188,189,220)'],\
[0.6, 'rgb(158,154,200)'],[0.8, 'rgb(117,107,177)'],[1.0, 'rgb(84,39,143)']]
data = [ dict(
type='choropleth',
colorscale = scl,
autocolorscale = False,
locations = temp['state_code'],
z = temp['num_proposals'].astype(float),
locationmode = 'USA-states',
text = temp['state_code'],
marker = dict(line = dict (color = 'rgb(255,255,255)',width = 2)),
colorbar = dict(title = "% of pro")
) ]
layout = dict(
title = 'Project Proposals % of Acceptance Rate by US States',
geo = dict(
scope='usa',
projection=dict( type='albers usa' ),
showlakes = True,
lakecolor = 'rgb(255, 255, 255)',
),
)
fig = dict(data=data, layout=layout)
offline.iplot(fig, filename='us-map-heat-map')
I have imported following libraries:
from chart_studio import plotly
import plotly.offline as offline
import plotly.graph_objs as go
offline.init_notebook_mode()
from collections import Counter
import chart_studio.plotly as py
Try the following code with your data:
(I tried putting your variables in the correct spots)
choropleth = go.Choropleth(
locations=temp['state_code'],
locationmode='USA-states',
z = temp['num_proposals'].astype(float),
zmin = 0,
zmax = max(temp['num_proposals'].astype(float)),
colorscale=scl,
autocolorscale=False,
text='Proposals',
marker_line_color='white',
colorbar_title="% Acceptance Rate"
)
fig = go.Figure(data=choropleth)
fig.update_layout(
title_text='Project Proposals % of Acceptance Rate by US States',
geo = dict(
scope='usa',
projection=go.layout.geo.Projection(type = 'albers usa'),
showlakes=True,
lakecolor='rgb(255, 255, 255)'),
)
fig.show()
This code works by creating the Plotly Choropleth Graph Object with your data, then loading that object into a Plotly Figure Graph Object, then updating the layout (for proper titles and zooms), and finally displaying the figure.

How to remove something from the Box in Plotly Python?

Which line of this code:
# Take credit amount values into a list
young = df['Credit_amount'].loc[df['Age_Group'] == 'Young'].values.tolist()
young_adults = df['Credit_amount'].loc[df['Age_Group'] == 'Young Adults'].values.tolist()
senior = df['Credit_amount'].loc[df['Age_Group'] == 'Senior'].values.tolist()
elder_credit = df['Credit_amount'].loc[df['Age_Group'] == 'Elder'].values.tolist()
# Create the box plots by age category
young_credit = go.Box(
y = young,
name = "Young",
jitter = 0.3,
pointpos = -1.8,
boxpoints = 'all',
marker = dict(
color = 'rgb(150, 198, 109)'),
line = dict(
color = 'rgb(111, 200, 37)')
)
young_adults_credit = go.Box(
y = young_adults,
name = "Young Adults",
jitter = 0.3,
pointpos = -1.8,
boxpoints = 'all',
marker = dict(
color = 'rgb(124, 236, 212)'),
line = dict(
color = 'rgb(38, 214, 177)')
)
senior_credit = go.Box(
y = senior,
name = "Seniors",
jitter = 0.3,
pointpos = -1.8,
boxpoints = 'all',
marker = dict(
color = 'rgb(241, 93, 93)'),
line = dict(
color = 'rgb(225, 44, 44)')
)
elder_credit = go.Box(
y = elder_credit,
name = "Elders",
jitter = 0.3,
pointpos = -1.8,
boxpoints = 'all',
marker = dict(
color = 'rgb(180, 121, 72)'),
line = dict(
color = 'rgb(115, 77, 46)')
)
data = [young_credit, young_adults_credit, senior_credit, elder_credit]
layout = dict(
title="Credit Amount by Age Group Segment",
xaxis = dict(title="Age Group"),
yaxis= dict(title="Credit Amount")
)
fig = dict(data=data, layout=layout)
iplot(fig, filename="Box Plot")
concerns the fragments marked in the picture below, I would like to remove those fragments from the chart and which lines of code I have to remove to achieve this goal.
I will be really thankfull for all clear answers because I can not find line of code to remove this fragments of plot.
Thank you so much!
If you Want to totally remove the points, you should remove parameters in each go.Box:
jitter = 0.3,
pointpos = -1.8,
boxpoints = 'all'
From plot.ly/python/box-plots/: With the points argument, display underlying data points with either all points (all), outliers only (outliers, default), or none of them (False).
Plot 1: boxpoints = False
Plot 2: boxpoints = 'all'
I got the same issue and can still not find the fix. The github issue is still open which Ahmed mentioned (https://github.com/plotly/plotly.js/issues/277).
Although, you can use a visible work around. It does not fix the problem! But for the vision it is fixed.
You van marker=dict(opacity=0) which makes the points invisible. When you hover over them, they are still there.

Python Plotly Error

It seems that the example code on the plotly website for choropleth maps is out of date and no longer works.
The error I'm getting is:
PlotlyError: Invalid 'figure_or_data' argument. Plotly will not be able to properly parse the resulting JSON. If you want to send this 'figure_or_data' to Plotly anyway (not recommended), you can set 'validate=False' as a plot option.
Here's why you're seeing this error:
The entry at index, '0', is invalid because it does not contain a valid 'type' key-value. This is required for valid 'Data' lists.
Path To Error:
['data'][0]
The code that I'm trying to run is shown below. It is copied as-is from the plotly website. Anyone have any ideas as to how I can fix it?
import plotly.plotly as py
import pandas as pd
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/2011_us_ag_exports.csv')
for col in df.columns:
df[col] = df[col].astype(str)
scl = [[0.0, 'rgb(242,240,247)'],[0.2, 'rgb(218,218,235)'],[0.4, 'rgb(188,189,220)'],\
[0.6, 'rgb(158,154,200)'],[0.8, 'rgb(117,107,177)'],[1.0, 'rgb(84,39,143)']]
df['text'] = df['state'] + '<br>' +\
'Beef '+df['beef']+' Dairy '+df['dairy']+'<br>'+\
'Fruits '+df['total fruits']+' Veggies ' + df['total veggies']+'<br>'+\
'Wheat '+df['wheat']+' Corn '+df['corn']
data = [ dict(
type='choropleth',
colorscale = scl,
autocolorscale = False,
locations = df['code'],
z = df['total exports'].astype(float),
locationmode = 'USA-states',
text = df['text'],
marker = dict(
line = dict (
color = 'rgb(255,255,255)',
width = 2
)
),
colorbar = dict(
title = "Millions USD"
)
) ]
layout = dict(
title = '2011 US Agriculture Exports by State<br>(Hover for breakdown)',
geo = dict(
scope='usa',
projection=dict( type='albers usa' ),
showlakes = True,
lakecolor = 'rgb(255, 255, 255)',
),
)
fig = dict(data=data, layout=layout)
url = py.plot(fig, filename='d3-cloropleth-map')
fig should be of the Figure type. Use the Choropleth graph object:
import plotly.graph_objs as go
...
data = [go.Choropleth(
colorscale = scl,
autocolorscale = False,
locations = df['code'],
z = df['total exports'].astype(float),
locationmode = 'USA-states',
text = df['text'],
marker = dict(
line = dict(
color = 'rgb(255,255,255)',
width = 2)),
colorbar = dict(
title = "Millions USD")
)]
...
fig = go.Figure(data=data, layout=layout)
...

Adding hover tool tip to bokeh histogram

I have created a histogram in bokeh using the following code:
TOOLS="pan,wheel_zoom,box_zoom,reset,hover"
for column in valid_columns:
output_file_name = str( file_name + column + ".html" )
data_values = stats[ column ].tolist()
output_file( output_file_name )
histogram, edges = np.histogram( data_values, bins=50 )
source = ColumnDataSource(
data = dict( data_value = data_values ) )
p1 = figure( title = column, background_fill="#E8DDCB", tools=TOOLS )
p1.quad( top = histogram, bottom = 0, left = edges[ :-1 ], right = edges[ 1: ],
fill_color = "#036564", line_color = "#033649" )
hover = p1.select(dict(type=HoverTool))
hover.tooltips = [ ( "Value", "#data_value" ) ]
show( p1 )
print( "Saved Figure to ", output_file_name )
where valid columns are a list of all columns I want examined within a pandas dataframe. I am trying to add a hover tool tip which will display the number of items stored in each bin but I have not be able to do so. Any help would be appreciated.
If you prefer to not use a ColumnDataSource, you can replace #data_value with #top and it should work with minimal editing:
hover = HoverTool(tooltips = [('Value', '#top')])
p.add_tools(hover)
i.e. editing the example histogram.py in this way also works:
from bokeh.models import HoverTool
def make_plot(title, hist, edges, x, pdf, cdf):
p = figure(title=title, tools='', background_fill_color="#fafafa")
p.quad(top=hist, bottom=0, left=edges[:-1], right=edges[1:],
fill_color="navy", line_color="white", alpha=0.5)
p.line(x, pdf, line_color="#ff8888", line_width=4, alpha=0.7, legend_label="PDF")
p.line(x, cdf, line_color="orange", line_width=2, alpha=0.7, legend_label="CDF")
p.y_range.start = 0
p.legend.location = "center_right"
p.legend.background_fill_color = "#fefefe"
p.xaxis.axis_label = 'x'
p.yaxis.axis_label = 'Pr(x)'
p.grid.grid_line_color="white"
hover = HoverTool(tooltips = [('Density', '#top')])
p.add_tools(hover)
return p
It looks like you are missing a couple of things:
Have a source of the same length as your histogram, not your data_values. To be more concrete, I think you want your source to be:
source = ColumnDataSource( data = dict( data_value = histogram ) )
Add the source to your p1.quad call, i.e.
p1.quad( top = histogram, bottom = 0, left = edges[ :-1 ], right = edges[ 1: ],
fill_color = "#036564", line_color = "#033649", source = source )

Categories